views:

140

answers:

2

ADTs in Haskell can automatically become instance of some typeclasses (like Show, Eq) by deriving from them.

data  Maybe a  =  Nothing | Just a
  deriving (Eq, Ord)

My question is, how does this deriving work, i.e. how does Haskell know how to implement the functions of the derived typeclass for the deriving ADT?

Also, why is deriving restricted to certain typeclasses only? Why can't I write my own typeclass which can be derived?

+2  A: 

From the Haskell 98 report:

The only classes in the Prelude for which derived instances are allowed are Eq, Ord, Enum, Bounded, Show, and Read...

Here's the description of how to derive these type classes: http://www.haskell.org/onlinereport/derived.html#derived-appendix

tibbe
+10  A: 

The short answer is, magic :-). This is to say that automatic deriving is baked into the Haskell spec, and every compiler can choose to implement it in its own way. There's lots of work on how to make it extensible however.

Derive is a tool for Haskell to let you write your own deriving mechanisms: http://community.haskell.org/~ndm/derive/

There's also a recent paper on how to bake this sort of generic deriving into compilers: http://www.dreixel.net/research/pdf/gdmh_draft.pdf

GHC also currently provides another sort of derivable type class extension, but its rarely used, as it is somewhat weak: http://www.haskell.org/ghc/docs/6.12.2/html/users_guide/generic-classes.html

sclv