case and list shapes in Haskell
Reads a corridor of traffic signals with case expressions over a sum type.
-- case tries each pattern top to bottom and takes the first match.
module Signals where
data Signal = Green | Yellow | Red | Dark
speedLimit :: Signal -> Int
speedLimit signal = case signal of
Green -> 45
Yellow -> 25
Red -> 0
_ -> 15
-- Lists match by shape: [] is empty, (x:xs) splits head from tail.
firstGreen :: [Signal] -> Int
firstGreen [] = 0
firstGreen (x:xs) = case x of
Green -> speedLimit x
_ -> firstGreen xs
How it works
case signal ofmatches theGreen,Yellow, andRedconstructors in turn.- A
_wildcard branch catchesDarkand falls back to the cautious limit. firstGreen []andfirstGreen (x:xs)split the empty list from head and tail.
Keywords and builtins used here
DarkGreenIntRedSignalYellow_casedatafirstGreenmoduleofspeedLimitwhere
The run, in numbers
- Lines
- 18
- Characters to type
- 438
- Tokens
- 67
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 54 seconds.
Step 1 of 3 in Pattern matching, step 7 of 27 in Language basics.