Pattern matching

The variables lesson showed that = matches the right side against the left side. This page takes the left side apart: a pattern is written in the shape of the data it accepts, and the match either binds every name in it or fails. Tuples, lists, maps and function heads all use the same idea, which is why Elixir can take a value apart without an index or a getter.

A pattern mirrors its data

A tuple pattern has the same number of elements as the tuple, and each position either names a value or states one. The pattern {:ok, code} accepts a two-element tuple whose first element is the atom :ok, and binds the second element to code:

tuple.exs

{:ok, code} = {:ok, 200} IO.puts("the code is #{code}") {a, b} = {1, 2} IO.puts(a + b)

elixir tuple.exs

the code is 200
3

The literal parts of a pattern are a test, not a binding: :ok has to be there or the whole match fails. The names are the holes that take the rest. A pattern never changes the value it matches; it only describes which values fit and what to call their pieces.

A list, head and tail

A list pattern uses square brackets, and the vertical bar splits the first element from the rest. [head | tail] binds one element and the list that remains, while a pattern of fixed length matches only a list of exactly that length:

list.exs

[head | tail] = [1, 2, 3] IO.inspect(head) IO.inspect(tail) [first, second] = [10, 20] IO.puts(first + second)

elixir list.exs

1
[2, 3]
30

The head and tail form is how a recursive function walks a list, and the recursion lesson builds one. A pattern with two names accepts a list of two elements and no more, so it is a length check as well as a destructuring. [] matches only the empty list and is the base case of that walk.

A map matches the keys it names

A map pattern names the keys it needs and ignores the rest, so it does not have to list the whole map. Every named key must be present; a key that is missing fails the match rather than binding nil:

map.exs

user = %{name: "Ada", age: 36, city: "London"} %{name: name, age: age} = user IO.puts("#{name} is #{age}") %{city: city} = user IO.puts(city)

elixir map.exs

Ada is 36
London

The first pattern names two of the three keys and the second names the third; neither has to know the whole shape. That is what makes a map the right choice for data that grows, and why a struct, which is a map with fixed keys, can be matched the same way.

A pattern in a function head

A function head is a pattern too. The clause runs only when the argument fits its shape, and the names in the head are bound for the body. Two clauses of one function can therefore accept two different shapes under one name:

function.exs

defmodule Greeter do def greet(%{name: name}), do: "hello #{name}" def greet(name), do: "hello #{name}" end IO.puts(Greeter.greet(%{name: "Ada", age: 36})) IO.puts(Greeter.greet("Grace"))

elixir function.exs

hello Ada
hello Grace

The first clause takes a map and reads its name; the second takes any other value and uses it as the name. The clauses are tried from the top, which is the rule the defaults and clauses lesson explains in full. A function that takes a pattern needs no type check in its body, because the head already refused every value that does not fit.

The mistake: a shape that does not fit

A pattern that does not fit raises MatchError and stops the program. The report shows the value that could not be matched, which is usually enough to see which side was wrong:

mismatch.exs

{:ok, value} = {:error, :down} IO.puts(value)

elixir mismatch.exs

** (MatchError) no match of right hand side value:

    {:error, :down}

    mismatch.exs:1: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The pattern wanted an ok tuple and the value was an error tuple, so no name was bound and the next line never ran. A program that expects either shape handles it with case, or with a match that keeps the tag and decides later. The error is early and loud, which is the point: a wrong shape does not travel through the program as a strange value.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a pattern do with the value on the right of =?

    Answer

    It accepts the value only if its shape fits, and binds the names in it

    A match either fits and binds, or fails with MatchError; there is no conversion.

  2. Which keys must a map pattern name?

    Answer

    The keys it needs, all of which must be present

    A map pattern is a partial match, but each named key has to exist.

  3. What does [head | tail] = [1, 2, 3] bind?

    Answer

    head to 1 and tail to [2, 3]

    The bar splits one element from the rest of the list.

  4. Where may a pattern appear besides the left side of =?

    Answer

    In a function head and in a case arm

    A function head and a case arm are patterns, and so is the left side of a with step.

  5. What does this program print? {a, b} = {3, 4} IO.puts(a * b)

    Answer

    12

    The pattern binds the two elements, and their product is 12.

  6. What does this program print? [h | t] = [1, 2, 3] IO.inspect({h, t})

    Answer

    {1, [2, 3]}

    The head is the first element and the tail is the list that remains.

  7. What does this program print? %{name: name} = %{name: "Ada", age: 36} IO.puts(name)

    Answer

    Ada

    A map pattern may name a subset of the keys, so the name is bound and printed.

  8. What does this program do? [_a, _b] = [1, 2, 3]

    Answer

    A MatchError, because a two-element pattern needs a list of two elements

    A fixed-length list pattern checks the length, and the list has three elements.

  9. What does this program do? %{age: _age} = %{name: "Ada"}

    Answer

    A MatchError, because the map has no age key

    Every key named in a map pattern must be present, and a missing key fails the match.

  10. What does this program print? x = 1 IO.puts(x) {x, y} = {2, 3} IO.puts(x + y)

    Answer

    1 / 5

    A name in a pattern rebinds, so x takes 2 and the sum is 5.

Article author: Arthur Isaev