Deriving strategies
Three ways to derive
A deriving clause asks for an instance the compiler writes. GHC has three strategies for writing it, and each means something different:
- stock: the instance GHC writes for this type by the standard rules, the same one deriving (Show) always meant.
- newtype: reuse the instance of the representation type, which is only possible for a newtype and is the GeneralizedNewtypeDeriving of older code.
- anyclass: write an empty instance and take every method from its default, which is what a class with all-default methods gives.
DerivingStrategies enables the keywords; without it, GHC picks a strategy from the class and the type, and the choice is not always the one the author meant. Writing the strategy is a promise to the reader that the instance is what it looks like.
deriving stock
The program wraps an Int in a count and asks for the standard Show and Eq, then for the numeric operations of the representation:
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main (main) where
newtype Count = Count Int
deriving stock (Show, Eq)
deriving newtype (Num)
main :: IO ()
main = do
print (Count 3 + Count 4)
print (Count 3 == Count 3)
ghc -Wall -O1 -o strata strata.hs
./strata
Count 7
True
deriving newtype
The + above is the Num Int instance applied through the wrapper, which is why the answer is Count 7 and not a syntax error. That is the whole value of the strategy:
- The representation is the same at run time, so the instance costs nothing and adds no boxing.
- Every method of the class comes from the representation, including the ones with subtle semantics such as fromInteger.
- The wrapper keeps its own type: a Count is not an Int, so a function that takes an Int still rejects it.
The old spelling is deriving (Num) with GeneralizedNewtypeDeriving enabled, and it still works; the strategy version says which instance was meant when a type could plausibly get one in two ways.
deriving anyclass
A class whose methods all have defaults can be derived for any type: the instance is empty and every method comes from the class. The example is a description that says nothing about the type it is given:
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DeriveAnyClass #-}
module Main (main) where
class Describe a where
describe :: a -> String
describe _ = "something"
data Point = Point Int Int
deriving anyclass (Describe)
main :: IO ()
main = putStrLn (describe (Point 1 2))
ghc -Wall -O1 -o anyclass anyclass.hs
./anyclass
something
The output is the default and not a description of the point, which is the honest result: the strategy did what it says. anyclass is the tool for marker classes and for serialisation classes with generic defaults, and it is a poor choice for a class whose methods have no default, where the compiler reports that it cannot derive.
Why the strategy is written
Without DerivingStrategies the compiler infers the strategy, and the inference depends on the class and the shape of the type. The two failure modes are worth knowing:
- A newtype with a class that has a default method can take either newtype or anyclass, and the compiler picks one; the two give different answers.
- A stock class on a newtype may silently use the representation, which is what newtype means, even when the author wanted the standard instance.
The strategy keyword removes the guess: the reader sees stock, newtype or anyclass and knows where the methods come from. The next lesson adds a fourth form, deriving via, which takes the instance from a third type chosen for the purpose.
Exercises
- Add Ord to the stock deriving of Count and compare two counts.
- Derive Semigroup and Monoid for a newtype over [String] with newtype.
- Write a class with one default method and one without, and try anyclass; read the error.
- Write the same program without DerivingStrategies and say which strategy the compiler picked.
- Explain why newtype is available for a newtype and not for a data type with several constructors.
- Compare a Count 7 with the number 7 and explain the type error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
deriving stockmean?Answer
The standard instance GHC writes for the type
stock is the ordinary derived instance, the one a plain deriving clause always gave.
-
What does
deriving newtype (Num)do fornewtype Count = Count Int?Answer
Reuses the Num instance of Int through the wrapper
The strategy takes the representation instance, which is why Count 3 + Count 4 is Count 7.
-
What does
deriving anyclassrequire?Answer
Every method of the class has a default
The instance is empty, so each method must come from the class default.
-
What does this program print?
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main (main) where newtype Count = Count Int deriving stock (Show) deriving newtype (Num) main :: IO () main = print (Count 2 * Count 5)Answer
Count 10
The Num instance of Int multiplies the two values and Show prints the wrapper.
-
Which extension enables the strategy keywords?
Answer
DerivingStrategiesDerivingStrategies is the syntax; the other two enable specific strategies.
-
What does this program print?
{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DeriveAnyClass #-} module Main (main) where class Marker a where mark :: a -> String mark _ = "marked" data T = T deriving anyclass (Marker) main :: IO () main = putStrLn (mark T)Answer
marked
The empty instance takes the default method, which returns marked.
-
Why is
Count 7not anInt?Answer
The newtype is a distinct type with the same representation
A newtype keeps its own type; only the representation is shared.
-
What does this program print?
module Main (main) where newtype Name = Name String deriving (Show) main :: IO () main = print (Name "ada")Answer
Name "ada"
The derived Show of the newtype prints the constructor and the string.
-
What ambiguity does the strategy keyword remove?
Answer
Between the stock instance and the instance of the representation
A newtype can plausibly get an instance in two ways, and the keyword says which.
-
What does this program print?
module Main (main) where newtype Count = Count Int deriving (Show, Eq) main :: IO () main = print (Count 3 == Count 4)Answer
False
The derived Eq compares the representation, and 3 is not 4.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev