Deriving strategies

The DerivingStrategies extension introduces two syntactic changes:

  1. A type definition can have multiple deriving clauses, not just one.
  2. Each deriving clause may optionally specify a deriving strategy that specifies which deriving mechanism to use for the classes listed in that clause.

A standard Haskell type definition using typeclass deriving looks like this:

The second line, deriving (Eq, Show), is called the deriving clause; it specifies that we want the compiler to automatically generate instances of the Eq and Show classes for our Pair type. The Haskell Report defines a handful of classes for which instances can be automatically generated.

Over the years, GHC has gradually added a number of additional deriving mechanisms via language extensions. Some extensions allow the deriving of one particular class; others are more general and can be used with any class.

Deriving strategies, introduced in GHC 8.2, brings them all together into a single more cohesive idea.

List of strategies

The strategies are:

  • stock: ‘Stock’ is used here to mean “standard”; stock deriving is the standard deriving strategy for standard typeclasses. This strategy works only for a handful of typeclasses in the base package, and the deriving mechanism is built into the compiler. Some of these are classes for which the deriving is specified in the Haskell Report (e.g. Eq and Show); others are classes for which GHC has added deriving support via language extensions (e.g Functor and Foldable). You do not usually need to use the stock keyword, but you may sometimes when you are using multiple deriving strategies and wish to explicitly resolve ambiguities.

  • anyclass: With the DeriveAnyClass extension enabled, this strategy generates an instance declaration with an empty body. This is only useful if the derived typeclass has default implementations for all methods (which, for a class defined using with the DefaultSignatures extension, is feasible).

  • newtype: With the GeneralizedNewtypeDeriving extension enabled, this strategy produces instances for a newtype that behave the same as the instances on the underlying type.

  • via: With the DerivingVia extension enabled, this strategy produces instances that behave the same as those of some other specified type, as long as the types receiving the instances is coercible with the type providing the instances.

Sign up for access to the full page, plus the complete archive and all the latest content.