DerivingStrategies extension introduces two syntactic changes:
- A type definition can have multiple
derivingclauses, not just one.
- 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
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
basepackage, 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.
Show); others are classes for which GHC has added deriving support via language extensions (e.g
Foldable). You do not usually need to use the
stockkeyword, but you may sometimes when you are using multiple
derivingstrategies and wish to explicitly resolve ambiguities.
anyclass: With the
DeriveAnyClassextension enabled, this strategy generates an
instancedeclaration 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
DefaultSignaturesextension, is feasible).
newtype: With the
GeneralizedNewtypeDerivingextension enabled, this strategy produces instances for a
newtypethat behave the same as the instances on the underlying type.
via: With the
DerivingViaextension 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.