wiki:DerivedInstances

Version 8 (modified by ross@…, 7 years ago) (diff)

link to GHC wiki page on stand-alone deriving

Derived Instances

Automatic derivation of instances is jolly useful. Current problems are:

  • Automatic derivation is only available for certain classes defined in the Prelude and standard libraries.
  • There is no way to specify how to derive a user-defined class in the general case.
  • There is no way to derive an instance of a class for a data type that is defined elsewhere (in another module).
  • There is no easy way to refer to the definitions that would have been derived when defining an explicit instance.
  • Deriving fails for some Haskell-98 data types. Try
    data Rose f a = Fork a (f (Rose f a)) deriving Show
    
    as an example.
  • Even in the absence of user-defined deriving, it should be easy for a newtype declaration to inherit some of the instances of its parent type, no matter where the class was defined, but this is currently only available as a GHC extension to Haskell 98 (see NewtypeDeriving).

User-specified derived instances

There are various extant proposals to enable the user-specification of the derivation of class instances:

Standalone derived instances

The development version of GHC adds a top-level declaration on the form:

'deriving' qtycls 'for' qtycon

which produces the same instance as would be produced by a deriving clause in a data or newtype declaration, but allows this derivation to be decoupled from the datatype declaration, e.g. in another module. See Stand-alone deriving declarations on the GHC Wiki.