Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 57 ยท Functions

Pattern Matching

Learn Haskell pattern matching: literals, tuples, lists, wildcards, as-patterns, case expressions and what happens with non-exhaustive patterns.

In many languages you decide what to do with a value by asking questions: is it empty, what is its first element, what is its length? In Haskell you usually describe the shape of the value instead, and the compiler works out which description fits. That is pattern matching, and it is the most characteristic piece of Haskell syntax.

You will use it in almost every function you write. This lesson covers patterns for literals, tuples and lists, wildcards, as-patterns, case expressions and the one danger to watch for: patterns that do not cover every value. You should know tuples and lists and function definitions.

Real Haskell code here is read-only because GHC is not installed on this site. The editors imitate pattern matching in JavaScript, with destructuring and switch, and say where the stand-in differs.

Several equations, one function

A function can be defined with several equations. Haskell tries them from top to bottom and uses the first one whose patterns match.

HASKELL
describe :: Int -> String
describe 0 = "zero"
describe 1 = "one"
describe n = "many (" ++ show n ++ ")"

The first two equations use literal patterns: they match only that exact value. The third uses a variable pattern: n matches anything and names it. Because the order matters, putting describe n first would make the other two equations unreachable.

Literals work for numbers, characters and strings. Strings are lists, so "yes" is a pattern that matches that exact string.

HASKELL
answer :: String -> Bool
answer "yes" = True
answer "no"  = False
answer _     = False

The underscore _ is the wildcard: it matches anything and does not bind a name. Use it for values you do not need, so readers (and the compiler's warnings) know you are ignoring them.

Tuple patterns

A tuple pattern mirrors the tuple's shape and names each component.

HASKELL
addPair :: (Int, Int) -> Int
addPair (x, y) = x + y

swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

firstOfThree :: (a, b, c) -> a
firstOfThree (x, _, _) = x

That is how you read values out of tuples bigger than a pair, where fst and snd do not work.

List patterns

Lists have two shapes: empty, [], or a head with a tail, x : xs. Pattern matching on those two shapes is the basis of almost every list function.

HASKELL
myLength :: [a] -> Int
myLength []       = 0
myLength (_ : xs) = 1 + myLength xs

safeHead :: [a] -> Maybe a
safeHead []      = Nothing
safeHead (x : _) = Just x

sumPairs :: [(Int, Int)] -> [Int]
sumPairs []             = []
sumPairs ((a, b) : rest) = (a + b) : sumPairs rest

Note the parentheses around x : xs in a function argument. Without them, myLength _ : xs would read as a function applied to two things. Patterns can be nested: the last example matches the head against a tuple pattern at the same time as splitting the list.

You can also match a list of a specific length by writing it out:

HASKELL
describeList :: [a] -> String
describeList []     = "empty"
describeList [_]    = "one element"
describeList [_, _] = "two elements"
describeList _      = "three or more"

[_, _] is shorthand for _ : _ : [].

As-patterns

Sometimes you want to take a value apart and keep the whole thing. An as-pattern, written name@pattern, binds the name to the entire matched value.

HASKELL
duplicateFirst :: [a] -> [a]
duplicateFirst []           = []
duplicateFirst whole@(x : _) = x : whole

-- duplicateFirst [1,2,3] == [1,1,2,3]

Without whole@, you would need to rebuild the list as x : xs and repeat yourself. As-patterns are especially useful in recursive functions that must pass the original input along unchanged.

Pattern kinds

Literal Matches one exact value.
Variable Matches anything and names it.
Wildcard _ Matches anything, no name.
Constructor Matches a shape like (x, y) or x : xs.
1 / 2

case expressions

Function equations are really sugar for case, which you can use anywhere an expression is allowed.

HASKELL
classify :: Int -> String
classify n = case compare n 0 of
  LT -> "negative"
  EQ -> "zero"
  GT -> "positive"

firstWord :: String -> String
firstWord text = case words text of
  []      -> ""
  (w : _) -> w

case examines one value and tries each alternative in turn. Each alternative is pattern -> expression, and all the expressions must have the same type, because the whole case is one expression. The alternatives must line up in the same column, which is the layout rule at work.

Use case when the thing you match on is the result of a computation, as with compare n 0 or words text, and not just a function argument. You can combine it with guards, which add Boolean conditions to a pattern.

Non-exhaustive patterns

If no equation matches, the program crashes at run time with a message like Non-exhaustive patterns in function describeList. The compiler does not stop you by default, but it can warn you: compile with -Wall (or -Wincomplete-patterns) and GHC lists the cases you forgot.

HASKELL
onlyZero :: Int -> String
onlyZero 0 = "zero"
-- onlyZero 5 crashes: no equation matches

The cure is to add a catch-all equation, or to return a Maybe and make the missing case explicit. Prefer making the type honest: safeHead above returns Nothing where Prelude's head would crash. For your own algebraic data types, pattern matching on every constructor with -Wall turned on means that adding a new constructor later makes the compiler point at every function that needs updating. That is one of the most valuable habits in Haskell.

Pattern matching on numbers with literals uses == behind the scenes, so it needs Eq (and Num) instances. You also cannot use the same variable twice in one pattern: f x x = ... is an error, not an equality test.

Trying the idea in JavaScript

JavaScript has destructuring but no first-match equations, so the stand-in below uses switch and array patterns. Real Haskell checks shapes for you and can warn about missing cases; here you must do both by hand.

JS Matching shapes by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A real compiler would also tell you that describe covers every Int because of its last equation. In JavaScript the default branch is your own responsibility.

The second stand-in models a tagged value and an as-pattern. Haskell's algebraic data types come later, so this uses plain objects with a tag field for a Maybe.

JS Maybe, as-patterns and case

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does Haskell try the equations of a function?

    The first matching equation wins, so specific patterns must come before general ones.
  2. 2. What does the pattern whole@(x : _) bind?

    An as-pattern gives a name to the whole matched value while the inner pattern still takes it apart.
  3. 3. What happens when no equation matches the argument?

    By default it is a run-time crash. Compiling with -Wall makes GHC warn about incomplete patterns.
  4. 4. Why does myLength (_ : xs) need parentheses around _ : xs?

    Function application binds tighter than the cons operator, so a cons pattern in an argument position must be parenthesised.
  5. 5. When is a case expression more convenient than function equations?

    Function equations match on arguments. case matches on any expression, such as words text or compare n 0.

Summary

  • A function can have several equations; the first one whose patterns match is used.
  • Patterns include literals, variables, the wildcard _, tuples, lists ([], x : xs, [a, b]) and nested combinations.
  • name@pattern keeps the whole value while also taking it apart.
  • case expressions match any expression, and all branches must share one type.
  • Missing cases crash at run time; turn on -Wall and prefer total functions that return Maybe.

Next, add conditions to your patterns and name intermediate values: Guards, where and let.