Notes (HPFP 06/31): Typeclasses

6 Typeclasses

6.2 What are typeclasses?

Sentences like these frustrate me. You can say nearly anything is the case “in a sense:”

“In a sense, the Moon really is made of cheese.” In the sense of poetic whimsy.

“In a sense, Johnny is at the top of his class.” In the sense of unexcused absences and missed assignments.

“In a sense, types and typeclasses are the same.” In the sense that they both specify and constrain the properties of expressions.

“In a sense, types and typeclasses are opposites.” In the sense that generation is opposed to consumption. The type definition is where you figure out how to make values; the typeclass definition is where you write interfaces that can use those values.

If an expression’s type is an instance of Eq it means there’s a way to define to define and equals function (==) to check if two expressions of that type are equal:

But there are types that it is impossible to define (==) for! The function constructor (->), for example, cannot be an instance of Eq. Why? The Halting Problem! If there’s no general way to test whether a function will halt on a given input, there’s certainly no general way to determine whether two functions will do the same thing (run forever or return the same value) for a given input.

So typeclasses constrains the potential things types can be by specifying what they can do.

Some typeclasses and their relationships:

6.5 Writing typeclass instances

The thing about writing your own instances vs deriving them automagically is that when you write your own you have control over what the instance does, whereas GHC can only derive them in one way.

For example, if I using the automatic deriving for the typeclass Show: