September 15, 2010

Typeclass implementation safety

I was reading up on Haskell's typeclasses last night and discovered something I had not realized before. The methods in a typeclass definition can reference other methods in the same definition. Take for instance the Eq typeclass definition:
class  Eq a  where
   (==), (/=) :: a -> a -> Bool
   x /= y = not (x == y)
   x == y = not (x /= y)
Given that the implementation of both functions is given in terms of the other one, an implementor of the typeclass only needs to implement one of the functions, getting the other one "for free." What caught my attention last night is the fact that the only way to know that this is the case for a given typeclass in to either read the source code for the typeclass definition, or hope that the documentation says something about it. In the case of the Eq typeclass, the documentation has the following blip about it:
Minimal complete definition: either == or /=.
It seems that currently the compiler is unable to help you know if you have implemented "enough" of a typeclass to make it safe to use. Maybe when my Haskell Kung Fu is stronger I can try to tackle this minor issue.

1 comment:

mightybyte said...

Hmmm, I didn't realize this. If the typeclass functions aren't given a default definition, then GHC will warn you. But it does not do a function dependency analysis on function definitions that are specified.