Instances, deriving and DerivingStrategies

deriving Eq, Ord and Show

The compiler writes an instance when the behaviour is the obvious one: field by field equality, field by field comparison, the constructor names for display. One clause derives several classes, and the classes that can be derived are the standard ones of the Prelude: Eq, Ord, Show, Read, Enum, Bounded, Semigroup, Monoid and a few more.

data Color = Red | Green | Blue deriving (Eq, Ord, Show)

The derived Ord for a type with no fields compares the constructors in the order they are declared: Red < Green < Blue. That is a decision the declaration makes, and reordering the constructors changes it, which is why a type whose order matters should say so in a comment or define the instance by hand.

module Main (main) where data Color = Red | Green | Blue deriving (Eq, Ord, Show) sortColors :: [Color] -> [Color] sortColors = foldr insertColor [] insertColor :: Color -> [Color] -> [Color] insertColor c [] = [c] insertColor c (x : xs) | c <= x = c : x : xs | otherwise = x : insertColor c xs main :: IO () main = do print (Red == Red) print (Red == Blue) print (Red < Blue) print (sortColors [Blue, Red, Green]) print (show Red)

ghc -Wall -O1 -o deriving deriving.hs
./deriving

True
False
True
[Red,Green,Blue]
"Red"

The insertion sort is written by hand to show that the derived <= is what orders the colors: the type got a total order from one clause, and the algorithm is four lines. In a real program the same is sort from Data.List.

An instance by hand

When the derived behaviour is not the right one, the instance is written like a class method. A point shows it: the derived Show would print Point 2 3, and this one prints a coordinate pair, which is what a user of the program sees.

module Main (main) where data Point = Point Int Int instance Show Point where show (Point x y) = "(" ++ show x ++ ", " ++ show y ++ ")" instance Eq Point where Point x1 y1 == Point x2 y2 = x1 == x2 && y1 == y2 main :: IO () main = do print (Point 2 3) print (Point 2 3 == Point 2 3) print (Point 2 3 == Point 3 2)

ghc -Wall -O1 -o manual manual.hs
./manual

(2, 3)
True
False

The Show instance has one method and the Eq instance needs ==; the compiler writes /= from it because the class gives it a default. An instance must be as complete as the class allows and as consistent as mathematics requires: an Eq that is not reflexive or an Ord that disagrees with it compiles and breaks the functions that rely on the laws.

DerivingStrategies

Once a type has several deriving clauses, it is not always obvious which mechanism produced each instance: the compiler itself, or the wrapped type of a newtype. DerivingStrategies makes it explicit with the words stock, newtype and anyclass.

{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main (main) where newtype UserId = UserId Int deriving stock (Show) deriving newtype (Eq, Ord) main :: IO () main = do print (UserId 3) print (UserId 3 == UserId 3) print (UserId 3 < UserId 4)

ghc -Wall -O1 -o strategies strategies.hs
./strategies

UserId 3
True
True

deriving stock is the ordinary deriving of the last section: Show prints the constructor and the wrapped number. deriving newtype takes the instance of the field type and reuses it, which is what GeneralizedNewtypeDeriving allows and why the comparisons work without a pattern match. The two words say which of the two behaviours the reader should expect, and a compiler warning asks for them when a newtype derives both ways.

The rules of an instance

The last rule is the one that bites in practice. A hand-written Ord that compares only one field, or an Eq that ignores a field, compiles and then makes nub, sort and every container behave surprisingly. The derived instance is the safe default; a manual one is justified when the domain has a rule the fields do not express.

Exercises

  1. Add Eq to Color and compare two colors without deriving Ord.
  2. Reorder the constructors of Color and predict what sortColors prints.
  3. Write a Show instance for a record of your own that prints name (age).
  4. Add a deriving newtype (Show) to UserId in place of the stock one and compare the output.
  5. Break the Eq instance of Point so that it compares only x, and explain which library functions start to misbehave.
  6. Explain the difference between deriving stock and deriving newtype in one sentence each.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does deriving (Eq, Ord, Show) ask the compiler for?

    Answer

    Instances that compare, order and print the value field by field

    The three derived instances use the fields and the constructor order.

  2. How does derived Ord order a type with no fields?

    Answer

    By the order the constructors are declared

    The declaration order is the comparison order, which is why reordering constructors changes it.

  3. What does this program print? module Main (main) where data Color = Red | Green | Blue deriving (Eq, Ord, Show) main :: IO () main = print (Red < Blue)

    Answer

    True

    Red is declared before Blue, so the derived Ord makes it smaller.

  4. What must a hand-written Show instance provide?

    Answer

    The show method for the type

    An instance implements the class methods, and Show has the single method show.

  5. What does deriving newtype (Eq, Ord) do?

    Answer

    Reuses the instances of the wrapped type

    The newtype strategy takes the field type instance, which is what GeneralizedNewtypeDeriving enables.

  6. What does this program print? module Main (main) where data Point = Point Int Int instance Show Point where show (Point x y) = "(" ++ show x ++ ", " ++ show y ++ ")" main :: IO () main = print (Point 2 3)

    Answer

    (2, 3)

    The hand-written show formats the two fields with parentheses and a comma.

  7. How many instances of one class can a type have in a program?

    Answer

    One

    The instance is selected from the type alone, so a second one would make the choice ambiguous.

  8. Where should an instance be defined?

    Answer

    In the module of the type or of the class

    The orphan rule keeps instances next to the type or class so they are found with it.

  9. What is the risk of a hand-written Eq instance?

    Answer

    It can break the laws, and functions such as nub rely on them

    The compiler checks the type, not reflexivity or consistency with Ord.

  10. What does deriving stock (Show) say to a reader?

    Answer

    The instance comes from the compiler, not from the wrapped type

    With DerivingStrategies the word names the mechanism, and stock is the ordinary compiler-written instance.

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