Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell handle overloading polymorphism?

I have a question about Haskell polymorphism.

As I've learned, there are two types of polymorphism:

  1. Parametric: where you do not specify the input type.

    Example:

     functionName :: [a] -> a
    
  2. Overloading: as imperative programming, i.e. passing different arguments to the same function.

My problem is: how does Haskell handle overloading?

like image 946
Sudantha Avatar asked Jul 09 '11 16:07

Sudantha


People also ask

Does Haskell support polymorphism?

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.

What is overloading in Haskell?

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.

What is an instance of a Haskell type class?

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.


1 Answers

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.

like image 119
hammar Avatar answered Sep 27 '22 21:09

hammar