Haskell Deriving
Deriving is asking Haskell to create standard operations for a custom type automatically. The deriving clause at the end of a data declaration names the typeclasses to create.
Derived Show and Eq work on Day values
Day is an enumeration, a type whose values are a fixed list of constructors. Deriving gives Mon a text form and gives the type ==.
data Day = Mon | Tue | Wed | Thu | Fri deriving (Show, Eq, Ord)
main :: IO ()
main = print (Mon, Mon == Tue, Wed == Wed)Derived Ord follows constructor order
Mon is declared before Tue, so Mon < Tue is True. Fri is declared after Wed, and compare on equal days gives EQ.
data Day = Mon | Tue | Wed | Thu | Fri deriving (Show, Eq, Ord)
main :: IO ()
main = print (Mon < Tue, Fri > Wed, compare Thu Thu)Derived Eq compares field by field
Book carries a String and an Int. Two Book values are equal only when both fields match.
data Book = Book String Int deriving (Show, Eq)
main :: IO ()
main = print (Book "Dune" 412 == Book "Dune" 412, Book "Dune" 412 == Book "Dune" 400)Example
data Day = Mon | Tue | Wed | Thu | Fri deriving (Show, Eq, Ord)
data Book = Book String Int deriving (Show, Eq)
firstDay :: Day
firstDay = Mon
chosen :: Day
chosen = Wed
main :: IO ()
main = print (chosen, firstDay < chosen, Book "Dune" 412 == Book "Dune" 412)Key points
- Deriving clause: deriving (Show, Eq, Ord) after a data declaration asks for three sets of operations.
- Derived Show: Show support gives the type a text form, so print can show its values.
- Derived Eq: Eq support gives == and /= for values of the type.
- Derived Ord: Ord support gives comparisons, and the order follows the order the constructors were declared.
- Fields and Eq: for a constructor with fields, derived Eq compares the fields one by one in order.
In this example, Day derives Show, Eq, and Ord, so Wed prints as Wed and Mon < Wed is True by constructor order. Book derives Eq, so two Book values with the same title and page count compare as equal. The main line prints all three results as one tuple.
Note
deriving works only for operations Haskell knows how to build, and each one must be named in the clause.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
For data Day = Mon | Tue | Wed | Thu | Fri deriving (Show, Eq, Ord), why is Mon < Wed True?