Version 9 (modified by simonmar@…, 8 years ago) (diff) |
---|

# Generalised deriving for newtype

## Brief Explanation

The `deriving` clause on a `newtype` can list any class. For any class except `Read`, `Show`, `Typeable` or `Data`, the instance is "the same" as for the wrapped type.

There are restrictions on the syntactic form of the `newtype`, and this mechanism also cannot be used with recursive newtypes.

## Examples

one area where this is particularly useful is when dealing with monad transformers. for example the jhc typechecking monad is declared as follows

data TcEnv = TcEnv { ... } newtype TI a = TI (ReaderT TcEnv IO a) deriving(Monad,MonadFix,MonadIO,MonadReader TcEnv,Functor)

and we end up with a complete monad with every interesting instance defined for free.

It is also good for selectively hiding properties of monad transformers

-- | Unique integer generator monad transformer. newtype UniqT m a = UniqT (StateT Int m a) deriving(Monad,MonadTrans, Functor, MonadFix, MonadPlus)

notice that while it uses a state transformer internally, the MonadState? class is intentionally left out of the deriving clause. this means that calls to the state monad will pass through the UniqT making stacking monads signifigantly easier.

A quick survey shows 34 different special purpose monads created in this fashion in jhc. This technique would not be possible without newtype deriving.

## References

- Generalised derived instances for newtypes in the GHC User's Guide

## Tickets

## Pros

- saves on repetitious boilerplate, significantly lowering the cost of
`newtype`

## Cons

- difficult to specify without saying "the same representation" (first attempt)
- difficult interactions with Type Families and GADTs, see http://hackage.haskell.org/trac/ghc/ticket/1496

## Comment

This proposal would make newtypes a bit more like type synonyms since they can be made to inherit properties of the underlying type, albeit (usefully) selectively. Having both type synonyms and newtype is a bit confusing, and the more alike they are, the more confusing it is. I guess looking for a single replacement is not an option for Haskell', but at least we should consider if automatic derivation for newtypes does not supersede TypeSynonymInstances as it would make it significantly less tiresome to introduce a newtype for purposes of abbreviation.