How does deriving work in Haskell?

Abhinav Sarkar picture Abhinav Sarkar · Oct 5, 2010 · Viewed 44k times · Source

Algebraic Data Types (ADTs) in Haskell can automatically become instances 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?

Answer

sclv picture sclv · Oct 5, 2010

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.

GHC used to provide a derivable type class extension called Generic Classes, but it was rarely used, as it was somewhat weak. That has now been taken out, and work is ongoing to integrate a new generic deriving mechanism as described in this paper: http://www.dreixel.net/research/pdf/gdmh.pdf

For more on this, see: