Wednesday, March 4, 2009

Typleclasses in Haskell

This post will try to demystify the part of the definition of the functions in the previous example before the "=>". For example, we had the definition

maxBy :: (Num t, Ord t) => Int -> [t] -> t

The function type tells us that we input an Int and a list of type ts and output a type t value.

Part of the beauty of Haskell is that one does not have to specify the type of input that we are dealing with when using maxBy.
However, in the function maxBy, we needed to take the maximum of a set of values, as well as take products of a set of values, so not just any type will do.

So, the type t input should allow one to tell when one value is larger than another, and should also make it possible to multiply values. This is where typeclasses come in. In the definition of maxBy, we tell the compiler to insist that any type t input must have typeclass Ord (to order the elements), and typeclass Num (to multiply the elements).

I won't go over this here, but one can easily create new data types that are instances of these types, provided one implements the operations that are built into Haskell for these types.

No comments:

Post a Comment