(forw) Re: [Haskell-cafe] deriving

John Dorsey haskell at colquitt.org
Mon Apr 7 15:08:31 EDT 2008


I meant to send this reply to the cafe.

----- Forwarded message -----

Date: Mon, 7 Apr 2008 15:05:00 -0400
To: PR Stanley <prstanley at ntlworld.com>
Subject: Re: [Haskell-cafe] deriving

Paul,

>         No, sorry. I'm not sure how this differs from my definition. 
> Could you elaborate please?

Gladly.  I haven't tested any of the code below, so pardon any typos
and thinkos.

It sounded like you were trying to say that Bool derives from Eq, Ord,
Show, and Read, and thus the keyword "from" would apply.  Of course,
I may have misunderstood your intent.

I was countering by saying that the "deriving" keyword indicates something
different.  I'll try to describe what I meant in a little more detail.

A type class definition defines properties of the type class.  Eg.,

class Example a where
    foo :: a
    bar :: a -> a

The class is then related to specific types by giving them instance
declarations.  The instance declarations can be explicit, as in

data Xyzzy = Xy | Zzy
instance Example Xyzzy where
    foo = Xy
    bar = const Zzy

Sometimes the instance declaration can be automatically derived instead,
which looks like:

-- non-working code, see below
data Xyzzy = Xy | Zzy
    deriving (Example)

This lets the compiler derive the "obvious" class instance declaration.
But it won't work for just any class, because the compiler needs to know
how to derive "obvious" instances.  A few classes have deriving
machinery "built-in":  Eq, Ord, Enum, Bounded, Show, Read.  

"deriving (Example)" won't work, since that machinery doesn't exist.

With effort, you could implement this "automatic derivation" machinery
for your own types, at least in GHC.  I've never needed it, so I've
never learned exactly how to do it.

In short, so "data Foo [...] deriving (Eq)" means: "define a new type Foo,
and automatically derive its class instance for Eq".

Does this help?

Regards,
John

----- End forwarded message -----


More information about the Haskell-Cafe mailing list