Haskell如何处理重载多态性? [英] How does Haskell handle overloading polymorphism?
问题描述
据我所知,有两种类型的多态:
-
参数:您不指定输入类型。 / p>
functionName :: [a] - >一个
-
重载:作为命令式编程,
Parametric: where you do not specify the input type.
Example:
functionName :: [a] -> a
Overloading: as imperative programming, i.e. passing different arguments to the same function.
我的问题是:Haskell如何处理重载?
使用类型类完成Haskell中的重载。例如,假设您要重载返回 Int
的函数 foo
:
class Fooable a where
foo :: a - > Int
实例Fooable Int其中
foo = id
实例Fooable Bool其中
foo _ = 42
然而,它们比大多数语言中的重载机制更强大。例如,你可以在返回类型上重载:
class Barable a where
bar :: Int - > a
实例Barable Int其中
bar x = x + 3
实例Barable Bool其中
bar x = x < 10
有关更多示例,请查看预定义的类型在Haskell中。
I have a question about Haskell polymorphism.
As I've learned, there are two types of polymorphism:
My problem is: how does Haskell handle overloading?
Overloading in Haskell is done using type classes. For example, let's say you want to overload a function foo
that returns an Int
:
class Fooable a where
foo :: a -> Int
instance Fooable Int where
foo = id
instance Fooable Bool where
foo _ = 42
However, they are more powerful than the overloading mechanisms found in most languages. For example, you can overload on the return type:
class Barable a where
bar :: Int -> a
instance Barable Int where
bar x = x + 3
instance Barable Bool where
bar x = x < 10
For more examples, have a look at the predefined type classes in Haskell.
这篇关于Haskell如何处理重载多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!