Chapter 4. Type Classes

Type classes are a means of polymorphism in Haskell. They allow us to provide a more abstract interface to our functions by declaring what properties parameters must have, not just their types.

4.1. More general types

What is the type of (+)?

Prelude> :type (+)
forall a. (Num a) => a -> a -> a

Lower case 'a' in this case is no longer just "any type", but rather it means any type such that the type is a "Num".

So we can write a function using the Num typeclass, sumTree. This function can sum up the elements of a tree as long as the elements are numbers. Thats a reasonable requirement, isn't it?:

sumTree :: (Num a) => Tree a -> a
sumTree (Leaf a) = a
sumTree (Branch t1 t2) = sumTree t1 + sumTree t2
sumTree Empty = 0

Prelude>:type myTree2
Tree Double
Prelude>:type myTree
Tree Integer

Prelude> sumTree myTree2
15.6415
Prelude> sumTree myTree
15