Typeclasses define a set of functions that can have different implementations depending on the type of data they are given. Typeclasses may look like the objects of object-oriented programming, but they are truly quite different.
Let’s use typeclasses to solve our
equality dilemma from the previous section. To begin with, we must
define the typeclass itself. We want a function that takes two
parameters, both the same type, and returns a
Bool indicating whether or not they are equal.
We don’t care what that type is, but we just want two items of that
type. Here’s our first definition of a typeclass:
-- file: ch06/eqclasses.hs class BasicEq a where isEqual :: a -> a -> Bool
This says that we are declaring a
BasicEq, and we’ll
refer to instance types with the letter
a. An instance type of this typeclass is any
type that implements the functions defined in the typeclass. This
typeclass defines one function. That function takes two parameters—both
corresponding to instance types—and returns a
The keyword to define a typeclass in
this may be confusing for those of you coming from an object-oriented
background, as we are not really defining the same thing.
On the first line, the name of the
a was chosen arbitrarily—we
could have used any name. The key is that, when you list the types of
your functions, you must use that name to refer to instance
Let’s look at this in ghci ...