next up previous contents
Next: User defined datatypes Up: Functional programming in Haskell Previous: Polymorphism   Contents

Conditional polymorphism

What would be the type of a sort function? The definition

  quicksort :: [a] -> [a]

is not accurate, because we cannot sort any list. We need to have a way of unambiguously comparing items in the list. This is not possible for arbitrary types because, for instance, a could be a function type and it is not always possible to effectively compare functions.

Consdier a simpler example--memberof that checks whether the value supplied as its first argument appears in the list supplied as its second argument. This should be of type

  memberof :: a -> [a] -> Bool

For this, we have to be able to check whether two elements of type a are equal. Even this is problematic for arbitrary types--again, what if a is a function type? Elementary computability theory tells us that checking whether two functions are equal (i.e., agree on all inputs) is undecidable.

To get around this, we have to place restrictions on the type of a. In Haskell, this is done by organizing the collection of all types into type classes (nothing to do with classes as in object-oriented programming!) A type class in Haskell is just a subset of all possible types. For instance, the type class Eq is the set of all types for which equality checking is possible. We can then write the type of memberof as

  memberof :: Eq a => a -> [a] -> Bool

This is to be read as ``memberof is of type a -> [a] -> Bool for any type a that belongs to the class Eq''.

In Haskell, the type class Ord contains all types on whichñ comparisons are possible. So, we would have

  quicksort :: Ord a => [a] -> [a]

Since comparing involves checking equality as well, clearly every type in Ord is also in Eq.

Recall that in Java, conditional polymorphism was achieved using interfaces. Unconditional polymorphism, at least for functions that operate on objects, can be achieved by defining the argument to be of type Object, which is compatible with all other classes in Java by the definition of the type hierarchy.


next up previous contents
Next: User defined datatypes Up: Functional programming in Haskell Previous: Polymorphism   Contents
Madhavan Mukund 2004-04-29