Haskell Pattern Matching
Pattern matching lets you define a function by describing the shapes its input can have, with one equation per shape. GHC tries the equations from top to bottom and uses the first one whose pattern fits. It is one of Haskell's most loved features, and it replaces most if chains.
describeCount :: Int -> String
describeCount 0 = "none"
describeCount 1 = "one"
describeCount 2 = "a couple"
describeCount _ = "many"
main :: IO ()
main = mapM_ (putStrLn . describeCount) [0, 1, 2, 7]none
one
a couple
many
The underscore _ is a wildcard: it matches anything and gives it no name. Because equations are tried in order, the catch-all must come last.
Kinds of patterns
| Pattern | Matches | Example |
|---|---|---|
| Literal | that exact value | 0, 'a', "yes", True |
| Variable | anything, and names it | n, name |
| Wildcard | anything, no name | _ |
| Tuple | a tuple, component by component | (x, y), (_, 0) |
| Empty list | [] |
[] |
| Cons | a non-empty list: its head and tail | (x : xs) |
| Fixed-length list | a list with exactly that many elements | [a, b] |
| Constructor | a specific constructor of a data type | Just v, Nothing, Left err |
| As-pattern | the whole value and its parts | all@(x : _) |
Matching on lists
A list is either empty [] or a head consed onto a tail x : xs. Covering both cases gives you safe functions that never crash:
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x : _) = Just x
describeList :: Show a => [a] -> String
describeList [] = "empty"
describeList [x] = "just " ++ show x
describeList [x, y] = "two: " ++ show x ++ " and " ++ show y
describeList (x : _ : _ : rest) = "starts with " ++ show x ++ ", " ++ show (length rest) ++ " after the third"
main :: IO ()
main = do
print (safeHead [5, 6, 7], safeHead ([] :: [Int]))
putStrLn (describeList ([] :: [Int]))
putStrLn (describeList [8])
putStrLn (describeList "hi")
putStrLn (describeList [1 .. 10])(Just 5,Nothing)
empty
just 8
two: 'h' and 'i'
starts with 1, 7 after the third
The naming convention x : xs ("x and the x-es") is universal in Haskell code. The parentheses around (x : xs) are required in a parameter: without them, the definition would be parsed as (safeHead x) : xs.
Matching on tuples
addPairs :: (Int, Int) -> (Int, Int) -> (Int, Int)
addPairs (a, b) (c, d) = (a + c, b + d)
quadrant :: (Double, Double) -> String
quadrant (0, 0) = "origin"
quadrant (_, 0) = "on the x-axis"
quadrant (0, _) = "on the y-axis"
quadrant (x, y)
| x > 0 && y > 0 = "I"
| x < 0 && y > 0 = "II"
| x < 0 = "III"
| otherwise = "IV"
main :: IO ()
main = do
print (addPairs (1, 2) (10, 20))
mapM_ (putStrLn . quadrant) [(0, 0), (3, 0), (2, 5), (-1, -1), (4, -2)](11,22)
origin
on the x-axis
I
III
IV
The last equation uses guards (|), which test conditions rather than shapes. They are the subject of the next lesson.
Matching on constructors
Bool, Maybe and your own data types are matched by their constructors:
toggle :: Bool -> Bool
toggle True = False
toggle False = True
orZero :: Maybe Int -> Int
orZero (Just n) = n
orZero Nothing = 0
main :: IO ()
main = do
print (toggle True)
print (map orZero [Just 4, Nothing, Just 9])
print (sum (map orZero [Just 4, Nothing, Just 9]))False
[4,0,9]
13
As-patterns
An as-pattern name@pattern gives you the whole value and its pieces at the same time:
firstLetter :: String -> String
firstLetter "" = "empty string"
firstLetter word@(c : _) = "The first letter of " ++ word ++ " is " ++ [c]
dedupe :: Eq a => [a] -> [a]
dedupe (x : rest@(y : _))
| x == y = dedupe rest
| otherwise = x : dedupe rest
dedupe xs = xs
main :: IO ()
main = do
putStrLn (firstLetter "lambda")
print (dedupe [1, 1, 2, 3, 3, 3, 1])
print (dedupe "bookkeeper")The first letter of lambda is l
[1,2,3,1]
"bokeper"
Incomplete patterns
If no equation matches, the program crashes at run time. GHC can warn you about missing cases at compile time (-Wincomplete-patterns, part of -Wall), so always cover every shape:
-- Dangerous: what about the empty list?
firstWord :: [String] -> String
firstWord (w : _) = wfirstWord [] would stop the program with "Non-exhaustive patterns in function firstWord". Add an equation for [], or return a Maybe String instead.
Tip: Order matters. A variable or
_pattern placed first matches everything, so the equations below it never run. GHC warns about such "redundant" equations.
Test yourself
What does the pattern (x : xs) match?
- Any list
- Only the empty list
- A non-empty list, naming its head
xand tailxs - A list of exactly two elements
Why should the wildcard equation f _ = ... come last?
- It is a syntax rule
- Equations are tried top to bottom and
_matches everything - Wildcards are slow
- It doesn't matter
In all@(x : _), what is all bound to?
- The head
- The tail
- The whole list
- A Boolean