Deriving strategies
- List of strategies
- Standalone deriving
- Resolving ambiguity
The DerivingStrategies
extension introduces two syntactic changes:
- A type definition can have multiple
deriving
clauses, 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 thebase
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
andShow
); others are classes for which GHC has added deriving support via language extensions (e.gFunctor
andFoldable
). You do not usually need to use thestock
keyword, but you may sometimes when you are using multiplederiving
strategies and wish to explicitly resolve ambiguities.anyclass
: With theDeriveAnyClass
extension enabled, this strategy generates aninstance
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 theDefaultSignatures
extension, is feasible).newtype
: With theGeneralizedNewtypeDeriving
extension enabled, this strategy produces instances for anewtype
that behave the same as the instances on the underlying type.via
: With theDerivingVia
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.