Deriving strategies
- List of strategies
- Standalone deriving
- Resolving ambiguity
The 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 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.
- GHC 6.8 -
DeriveDataTypeable,GeneralizedNewtypeDeriving - GHC 7.2 -
DeriveGeneric,DeriveLift - GHC 7.10 -
DeriveAnyClass,DeriveFoldable,DeriveFunctor,DeriveTraversable - GHC 8.6 -
DerivingVia
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 thebasepackage, 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.EqandShow); others are classes for which GHC has added deriving support via language extensions (e.gFunctorandFoldable). You do not usually need to use thestockkeyword, but you may sometimes when you are using multiplederivingstrategies and wish to explicitly resolve ambiguities.anyclass: With theDeriveAnyClassextension enabled, this strategy generates aninstancedeclaration 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 theDefaultSignaturesextension, is feasible).newtype: With theGeneralizedNewtypeDerivingextension enabled, this strategy produces instances for anewtypethat behave the same as the instances on the underlying type.via: With theDerivingViaextension 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.

