Course map
Haskell // 07

Pattern matching

Read

Equations and case

A function can be defined by several equations, one per pattern. The first pattern that fits the argument wins.

describe :: Int -> String
describe 0 = "zero"
describe 1 = "one"
describe n = "many"

firstOr :: Int -> [Int] -> Int
firstOr fallback []      = fallback
firstOr _        (x : _) = x

The list patterns [] and x : rest match the empty list and a list with at least one element, naming its head x. An underscore matches anything without naming it.

The same thing as an expression is case:

sign :: Int -> String
sign n = case compare n 0 of
  LT -> "negative"
  EQ -> "zero"
  GT -> "positive"
01 / 05