[Haskell-cafe] deriving

PR Stanley prstanley at ntlworld.com
Mon Apr 7 19:29:28 EDT 2008


Hi,
Thank you very much for your helpful replies.
So, we define (or is it declare) a class with a polymorphic value(s 
which will be used in defining function types or functions associated 
with that class. The data types are then used for deriving instances 
of that class specific to each data type. The function defined in the 
general class can be redefined if necessary.  It sort of reminds me 
of specialisation in OO. Get thee behind me beast. :-)

Any comments?

Cheers,
Paul


At 20:05 07/04/2008, you wrote:
>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:
>
>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



More information about the Haskell-Cafe mailing list