[Haskell-cafe] Deriving

wren ng thornton wren at freegeek.org
Tue Dec 2 22:28:50 EST 2008

Daryoush Mehrtash wrote:
> What happens when a type adds driving such as:
> newtype SupplyT s m a = SupplyT (StateT [s] m a)
>     deriving (Functor, Monad, MonadTrans, MonadIO)
> Two questions:
> How does the deriving implement the instance?

With GeneralizedNewtypeDeriving, since newtypes are just a 
reinterpretation of the underlying type, the deriving clause just uses 
the instance for the underlying type (massaging it with the 
wrapping/unwrapping functions for the newtype). The primary use for this 
is for defining a newtype on monad transformer stacks, for which it 
succeeds excellently. However, if the semantics of your newtype are 
different than the underlying type w.r.t. the type class, then it's not 
so good.

For the more basic kind of deriving clause, the compiler knows about how 
to create generic instances for obvious things, e.g. the compiler can 
derive the obvious Show instance by doing introspection on the source 
code. However, these derivations are limited to classes with an obvious 
implementation based solely on the structure of the type definition.

Live well,

More information about the Haskell-Cafe mailing list