Pattern matching
One equation per shape
A function is not a single body: it is a list of equations, and the compiler picks the first whose pattern matches the arguments. Patterns are not only variables: a literal, a constructor or a list shape is a pattern too, and a variable is the pattern that matches anything.
module Main (main) where
classify :: Int -> String
classify 0 = "zero"
classify 1 = "one"
classify _ = "many"
main :: IO ()
main = do
putStrLn (classify 0)
putStrLn (classify 1)
putStrLn (classify 7)
ghc -Wall -O1 -o equations equations.hs
./equations
zero
one
many
The order is the semantics. If the third equation came first, it would match everything and the other two would be dead code, which GHC reports as an overlapping pattern. The last equation here is the catch-all: a variable or the wildcard, which is the variable you do not name. Without it the function would be partial, and the next but one section shows the warning that follows.
The wildcard
_ is a pattern that matches any value and binds nothing. Use it when the value is not needed, both to say so and to keep -Wall quiet: a named argument that the body never uses is an unused match, and naming it suggests to the reader that it matters.
ignoreSecond :: a -> b -> a
ignoreSecond first _ = first
isZero :: Int -> Bool
isZero 0 = True
isZero _ = False
The two equations of isZero are the standard shape of a predicate over a sum type: one equation per constructor or literal, and a wildcard for everything else. It is the same idea as the guarded otherwise from the lesson on if, written one level lower: a guard tests a condition, a pattern tests a shape.
List patterns and as-patterns
A list pattern is written with the cons constructor, so (x : xs) names the head and the tail and [] is the empty list. A pattern can also name the whole value and its parts at once: all@(x : xs) binds all to the full list and x and xs to its parts, which saves rebuilding the list from them.
module Main (main) where
headOr :: a -> [a] -> a
headOr fallback [] = fallback
headOr _ (x : _) = x
duplicate :: [a] -> [a]
duplicate [] = []
duplicate whole@(x : _) = x : whole
main :: IO ()
main = do
print (headOr (0 :: Int) [])
print (headOr 0 [7, 8] :: Int)
print (duplicate [1, 2, 3] :: [Int])
print (duplicate "ab" :: String)
ghc -Wall -O1 -o aspatterns aspatterns.hs
./aspatterns
0
7
[1,1,2,3]
"aab"
headOr is the total replacement for head that the lesson on lists asked for: the empty case has an answer instead of a crash. duplicate shows the as-pattern: the result is the head followed by the whole original list, which would be written x : x : xs without it, and would have to rebuild the list for a longer function.
When the patterns do not cover
Patterns are checked against the type, and GHC can tell when a case is missing. Here is a function that handles a one-element list and a list of at least two elements, but not the empty one:
module Main (main) where
label :: [Int] -> String
label [x] = "one: " ++ show x
label (x : y : _) = "several: " ++ show x ++ ", " ++ show y
main :: IO ()
main = putStrLn (label [1, 2])
ghc -Wall -O1 -o incomplete incomplete.hs
./incomplete
incomplete.hs:4:1: warning: [GHC-62161] [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for 'label':
Patterns of type '[Int]' not matched: []
|
4 | label [x] = "one: " ++ show x
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
several: 1, 2
The build succeeds: this is a warning, not an error, and the program runs and prints its line. The warning names the missing pattern exactly, and the call that would trigger it is label [], which dies at run time with a pattern-match failure. -Wall includes -Wincomplete-patterns, so a build without this warning is a promise that the case analysis is complete for the type as it is defined today.
That promise has a condition worth knowing: GHC checks the constructors that exist when the function is compiled. Add a constructor to a data type in another module and the old function is no longer exhaustive, but it was compiled before the constructor existed, so the warning is not retroactive. Rebuilding the project after the change brings it back, which is one more reason to keep warnings at zero: the day a case becomes incomplete, the warning shows up in the build of the module that has the gap.
The program
The lesson page has shown three separate programs; this is the same material in one file, built and run as one, with the two functions that are total and the one that is not:
module Main (main) where
classify :: Int -> String
classify 0 = "zero"
classify 1 = "one"
classify _ = "many"
headOr :: a -> [a] -> a
headOr fallback [] = fallback
headOr _ (x : _) = x
main :: IO ()
main = do
mapM_ (putStrLn . classify) [0, 1, 7]
print (headOr (0 :: Int) [] :: Int)
ghc -Wall -O1 -o matching matching.hs
./matching
zero
one
many
0
The build is clean and hlint says No hints. The compose operator putStrLn . classify is the one the lesson on higher-order functions takes apart; here it only saves a lambda inside mapM_.
Exercises
- Write sign as three equations on 0, a negative literal and a wildcard, instead of guards.
- Write second :: [a] -> Maybe a with patterns for [], [_] and (_ : x : _).
- Rewrite duplicate without an as-pattern and count how many times the list is written.
- Remove the [] equation from headOr and read the GHC-62161 warning.
- Write a function on (Int, Int) with a pattern for a pair whose components are equal and a wildcard for the rest.
- Explain why an equation that matches everything above a specific one makes the specific one unreachable.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How does Haskell choose between several equations for one function?
Answer
Top to bottom: the first equation whose patterns match runs
Equations are tried in source order, so a catch-all above a specific pattern shadows it.
-
What does
classify 7print in the lesson program?Answer
many
The literal patterns 0 and 1 do not match, and the wildcard equation answers "many".
-
What is the pattern
(x : xs)?Answer
A non-empty list: x is the head, xs the tail
The cons pattern splits a list into its first element and the rest, whatever the length of the rest.
-
What does the wildcard
_bind?Answer
Nothing: it matches any value and names none
The wildcard matches without binding, which says the value is not used and keeps -Wall quiet.
-
What does this program print?
module Main (main) where headOr :: a -> [a] -> a headOr fallback [] = fallback headOr _ (x : _) = x main :: IO () main = print (headOr (0 :: Int) [] :: Int)Answer
0
The empty list matches the first equation, which returns the fallback value instead of failing.
-
What does
whole@(x : _)bind?Answer
whole to the full list and x to its head
An as-pattern names the whole value being matched and also the parts named inside the pattern.
-
What does
-Wallsay about a function whose patterns miss[]?Answer
A GHC-62161 warning listing the missing pattern
Incomplete patterns are a warning under -Wall; the program still builds and fails only if the missing case is reached.
-
What does this program print?
module Main (main) where label :: [Int] -> String label [x] = "one: " ++ show x label (x : y : _) = "several: " ++ show x ++ ", " ++ show y main :: IO () main = putStrLn (label [1, 2])Answer
several: 1, 2
A two-element list does not match [x], so the second equation runs and names the first two elements.
-
Why does an equation with a wildcard argument above a literal equation break the literal one?
Answer
The wildcard matches every value, so the later equation is never reached
Matching is top to bottom, and a wildcard matches the values the literal would have matched.
-
Which function is the total replacement for
head?Answer
headOr fallback (x : _) = xwith a case for[]A pattern match with an explicit empty case gives an answer for every list, so the function is total.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev