[Haskell-beginners] Defining an instance: Syntax that works exactly sometimes

Michael Orlitzky michael at orlitzky.com
Thu Jan 22 00:51:39 UTC 2015

On 01/21/2015 07:23 PM, Jeffrey Brown wrote:
>     data Dirn = Succ | Pred
>         deriving (Eq, Show, Ord)

When you "derive" a typeclass instance, you get it magically for free.
So you don't need to do this:

>     -- implement Ord
>     (<=) Succ Pred = False
>     (<=) _ _ = True

> But if I try to define the Rev instance the same way the Ord instance is
> being defined, it does not compile:
> ...
>        deriving (Eq, Show, Ord, Rev)

But you can't derive classes that you've defined yourself, it only works
for predefined ones. (That's how the compiler can do it magically.) So
"deriving (Rev)" won't work, because you made the "Rev" typeclass yourself.

In the second case, you have to do:

    instance Rev Dirn where
      rev Succ = Pred
      rev Pred = Succ

because you can't derive Rev, because it isn't a predefined typeclass.

One more thing: when "deriving (Ord)", the compiler uses the order that
you've typed the constructors in. So actually, the derived instance
would have Succ <= Pred, probably not what you want. I'd switch it to
"Pred | Succ" if I were you.

The details of why all this failed in a confusing way have been
explained in the other responses.

More information about the Beginners mailing list