I have a question about Haskell polymorphism.
As I've learned, there are two types of polymorphism:
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.
My problem is: how does Haskell handle overloading?
Polymorphism is widespread in Haskell and is a key feature of its type system. Most polymorphism in Haskell falls into one of two broad categories: parametric polymorphism and ad-hoc polymorphism.
A symbol is overloaded if it has two (or more) meanings, distinguished by type, that are resolved at compile time. For example, in Haskell, as in many other languages, the operator + has (at least) two distinct implementations associated with it, one of type Int -> Int -> Int, the other of type Float -> Float -> Float.
An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With