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
data Direction = North | East | South | Westgives the type exactly four values, andderiving (Show, Eq)supplies both instances.bearinghas one equation per constructor, which makes the match exhaustive without a catch-all.isOnshorecompares values with(==), available only becauseEqwas derived, andmainprints both results.
Keywords and builtins used here
BoolDirectionEastEqIOIntNorthShowSouthWestbearingdataderivingdoisOnshoremain
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.
Step 1 of 3 in Types & records, step 16 of 27 in Language basics.