typestar

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

  1. case signal of matches the Green, Yellow, and Red constructors in turn.
  2. A _ wildcard branch catches Dark and falls back to the cautious limit.
  3. firstGreen [] and firstGreen (x:xs) split the empty list from head and tail.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Pattern matching, step 7 of 27 in Language basics.

← Previous Next →