[Haskell-beginners] Ensuring consistency in typeclass instances?

Brent Yorgey byorgey at seas.upenn.edu
Tue Nov 25 13:59:13 EST 2008

On Tue, Nov 25, 2008 at 05:52:06PM +0000, Colin Paul Adams wrote:
> Hello,
> I'm just reading through Real World Haskell - chapter 6 (typeclasses).
> The definition of Eq is shown, and it mentions that you can define
> either one or both of the two classes.
> What would happen if I were two define both == and /= for an instance,
> in such a way that they were not opposites?
> If I were doing this in Eiffel, the function definitions would have
> postconditions to state the relationships, and the first execution
> would trigger a violation, telling me what was wrong. Is there any
> similar facility in Haskell?

Nope.  You will just get (possibly) inconsistent results.  There are
many other typeclasses like this as well (Functor, Monoid, Monad...)
where the methods are supposed to satisfy certain laws about how they
relate to one another, but Haskell has no way to guarantee this.

A meta-level point is that Haskell (and strongly-typed languages in
general) are all about *static* (compile-time) verification.  Having a
program which dynamically (at run-time) checks that certain properties
hold, a la Eiffel, is generally a rather un-Haskellish way of doing
things.  As much as possible, I would like to know for sure that if my
Haskell program compiles, it will not exhibit any run-time errors.

So, to check constraints statically rather than dynamically, they must
be put in the type system.  But the sorts of constraints you're asking
about (type class laws) often need dependent types (which Haskell
doesn't have) to be expressed elegantly.


More information about the Beginners mailing list