typestar

Sum types in Haskell

A sum type lists every value the type can hold, and deriving writes the printing and comparison code.

-- a sum type lists its alternatives; deriving asks GHC to write the
-- Show and Eq instances so these values can print and compare
data Direction = North | East | South | West
  deriving (Show, Eq)

-- one equation per constructor, which makes the match exhaustive
bearing :: Direction -> Int
bearing North = 0
bearing East = 90
bearing South = 180
bearing West = 270

-- (==) works on Direction only because Eq was derived above
isOnshore :: Direction -> Bool
isOnshore d = d == East || d == South

main :: IO ()
main = do
  print (map bearing [North, East, South, West])
  print (South, isOnshore South)

How it works

  1. data Direction = North | East | South | West gives the type exactly four values, and deriving (Show, Eq) supplies both instances.
  2. bearing has one equation per constructor, which makes the match exhaustive without a catch-all.
  3. isOnshore compares values with (==), available only because Eq was derived, and main prints both results.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
600
Tokens
84
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 3 in Types & records, step 16 of 27 in Language basics.

← Previous Next →