TExcelTAD
Home › Elixir › Elixir Pattern Matching

Elixir Pattern Matching

In most languages = means "assign". In Elixir = is the match operator: it checks that the value on the right fits the pattern on the left, and binds any variables in the pattern along the way. Pattern matching is the single most important idea in Elixir; you will use it in function heads, case, with, receive and almost everywhere else.

Binding variables

When the left side is a plain variable, the match always succeeds and the variable is bound:

elixir · try it yourself
x = 1
IO.inspect(x)

# 1 = x is also a valid match: the value of x matches the literal 1
1 = x
IO.puts("1 = x matched")

x = 2          # rebinding a name is allowed
IO.inspect(x)
1
1 = x matched
2

The data itself never changes. x = 2 does not modify the old value; it makes the name x point to a new one.

Destructuring tuples and lists

A pattern can mirror the shape of the data. Variables inside the pattern pick up the matching parts:

elixir · try it yourself
{status, message} = {:ok, "file saved"}
IO.inspect(status)
IO.inspect(message)

[first, second, third] = ["red", "green", "blue"]
IO.puts(second)
IO.puts("#{first} and #{third}")

{:user, name, age} = {:user, "Lin", 31}
IO.puts("#{name} is #{age}")
:ok
"file saved"
green
red and blue
Lin is 31

Literals in a pattern (like the atom :user) must be equal to the corresponding value. This is how Elixir code checks tags: {:ok, value} = result only succeeds when the result really starts with :ok.

When a match fails

If the shapes or the literals don't fit, a MatchError is raised:

elixir · try it yourself
result = {:error, :enoent}

try do
  {:ok, contents} = result
  IO.puts(contents)
rescue
  e in MatchError -> IO.puts(Exception.message(e))
end

try do
  [a, b] = [1, 2, 3]
  IO.inspect({a, b})
rescue
  e in MatchError -> IO.puts(Exception.message(e))
end
no match of right hand side value:

    {:error, :enoent}

no match of right hand side value:

    [1, 2, 3]

In real code you usually don't rescue MatchError. Instead you use case to try several patterns, which you will see in the next lessons.

Head and tail of a list

The pattern [head | tail] splits a non-empty list into its first element and the rest. It is the basis of recursion over lists:

elixir · try it yourself
[head | tail] = [10, 20, 30]
IO.inspect(head)
IO.inspect(tail)

[a, b | rest] = [1, 2, 3, 4, 5]
IO.inspect({a, b, rest})

[only | empty] = [:one]
IO.inspect({only, empty})
10
[20, 30]
{1, 2, [3, 4, 5]}
{:one, []}

[h | t] does not match an empty list [], because an empty list has no head.

Matching maps

A map pattern only needs to mention the keys you care about. Extra keys in the value are ignored:

elixir · try it yourself
user = %{name: "Noor", role: :admin, email: "noor@example.com"}

%{name: name, role: role} = user
IO.puts("#{name} has role #{role}")

%{} = user   # an empty map pattern matches any map
IO.puts("it is a map")
Noor has role admin
it is a map

The underscore

_ matches anything and throws the value away. Variables starting with an underscore (_ignored) also match anything; the name documents what you are skipping and silences the "unused variable" warning.

elixir · try it yourself
{_, _, year} = {"14", "July", 1789}
IO.inspect(year)

{:ok, _body, headers} = {:ok, "<html>…</html>", [{"content-type", "text/html"}]}
IO.inspect(headers)
1789
[{"content-type", "text/html"}]

Summary

Pattern Matches
x anything, binds x
_ / _name anything, ignores it
42, :ok, "text" only that exact value
{a, b} a 2-element tuple
[a, b] a list of exactly 2 elements
[h | t] a non-empty list
%{key: v} a map that has :key
"prefix" <> rest a string starting with "prefix"

Test yourself

What is tail after [head | tail] = [5]?

  1. 5
  2. nil
  3. []
  4. It raises MatchError

Which match raises a MatchError?

  1. {a, b} = {1, 2}
  2. %{x: x} = %{x: 1, y: 2}
  3. [a, b] = [1, 2, 3]
  4. _ = :anything

What does 1 = x do when x is 1?

  1. Assigns 1 to x
  2. Raises a syntax error
  3. Succeeds, because the value of x matches the pattern 1
  4. Changes the value of 1