Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 48 ยท Core Language

Pattern Matching: The = Operator

Understand Elixir's match operator: destructure tuples, lists and maps, ignore parts with _, use the pin operator ^, and read a MatchError. Includes a JS matcher.

In most languages, = means "store this value in that variable". In Elixir, = is the match operator. It tries to make the left side fit the right side, and in doing so it can bind variables. When the shapes do not fit, the program raises an error. This one idea replaces a surprising amount of other languages' machinery: unpacking values, checking that data has the expected form, and choosing between branches.

In this lesson you will use = to destructure tuples, lists and maps, ignore parts you do not need, keep a variable fixed with the pin operator, and read the MatchError you get when a match fails. The Elixir code is read-only on this site; the TryIts are JavaScript stand-ins, and the first one is a miniature matcher so you can watch the rules work.

What = really does

Fit the shapes Left side is a pattern, right side is a value.
Bind names Unbound variables take the matching part.
Or fail No fit means a MatchError.
1 / 2

The match operator

Start with something that looks like assignment:

ELIXIR
iex> x = 1
1
iex> x
1

x was unbound, so Elixir bound it to 1 to make the match succeed. But the left side is allowed to contain values too:

ELIXIR
iex> 1 = x
1
iex> 2 = x
** (MatchError) no match of right hand side value: 1

1 = x succeeds because x is 1. 2 = x fails: there is no way to make the literal 2 equal 1. A MatchError is not a quirk; it is how Elixir says "the data did not have the shape you described".

Destructuring tuples

A tuple pattern takes a tuple apart by position:

ELIXIR
iex> {a, b} = {1, 2}
iex> a
1
iex> b
2
iex> {:ok, value} = {:ok, 42}
iex> value
42
iex> {:ok, value} = {:error, :not_found}
** (MatchError) no match of right hand side value: {:error, :not_found}

The {:ok, value} pattern is the classic: it asserts that the result is a success and extracts the payload in one line. If the function returned an error tuple instead, the match fails right there, which stops bad data from travelling further into your program. Later lessons turn this into everyday error handling with case and with.

The sizes must also agree: {a, b} = {1, 2, 3} raises a MatchError, because a 2-tuple pattern cannot fit a 3-tuple.

Destructuring lists

Lists match element by element, and the cons form [head | tail] splits off the first element:

ELIXIR
iex> [first, second, third] = [10, 20, 30]
iex> second
20
iex> [head | tail] = [1, 2, 3]
iex> head
1
iex> tail
[2, 3]
iex> [a, b | rest] = [1, 2, 3, 4, 5]
iex> rest
[3, 4, 5]
iex> [head | tail] = []
** (MatchError) no match of right hand side value: []

An empty list has no head, so it cannot match [head | tail]. This is the reason recursive functions on lists always have a clause for []; see recursion. The tail of a one-element list is the empty list: [x | t] = [5] gives x = 5 and t = [].

Destructuring maps

Map patterns are partial: the pattern lists the keys you care about, and the map may have more.

ELIXIR
iex> user = %{name: "Ana", age: 31, role: :admin}
iex> %{name: name} = user
iex> name
"Ana"
iex> %{name: n, role: r} = user
iex> {n, r}
{"Ana", :admin}
iex> %{email: email} = user
** (MatchError) no match of right hand side value: %{age: 31, name: "Ana", role: :admin}

The match fails only when a key in the pattern is missing. Extra keys are ignored. This makes map patterns a convenient way to pull a few fields out of a larger record; maps and structs covers them fully.

Ignoring parts with _

Use the underscore for a part you do not care about. It matches anything and binds nothing, so you can use it as many times as you like in one pattern:

ELIXIR
iex> {_, second, _} = {:a, :b, :c}
iex> second
:b
iex> [_ | tail] = [1, 2, 3]
iex> tail
[2, 3]
iex> {:ok, _} = {:ok, "anything here"}

A name that starts with an underscore, such as _reason, is a normal variable that tells the compiler (and your reader) that you know it is unused. It avoids the "unused variable" warning while still documenting what is being ignored.

Variables rebind, repeated names must agree

A variable on the left side is bound to whatever fits. If it already has a value, it is simply rebound to the new one:

ELIXIR
iex> x = 1
iex> x = 2
iex> x
2

Inside a single pattern, though, using the same variable twice means the two spots must hold the same value:

ELIXIR
iex> {x, x} = {5, 5}
iex> x
5
iex> {y, y} = {5, 6}
** (MatchError) no match of right hand side value: {5, 6}

The pin operator

Sometimes you do not want to rebind an existing variable; you want to match against its current value. Put the pin operator ^ in front of the name:

ELIXIR
iex> expected = 5
iex> ^expected = 5
5
iex> ^expected = 6
** (MatchError) no match of right hand side value: 6
iex> {^expected, other} = {5, :ok}
iex> other
:ok

Without the pin, expected = 6 would just rebind the variable. With the pin, it asserts. This matters most when you check incoming data against something you already know, such as an ID in a message.

Here is a miniature matcher in JavaScript. It models tuples, lists with a tail, maps, _, and pins, and it raises a MatchError. It is not how Elixir is implemented, but the rules it follows are the ones you just read.

JS Stand-in: a tiny pattern matcher

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

No output.

What matching is not

JavaScript has destructuring that looks similar, but it never fails: const [a, b] = [1] quietly gives b the value undefined. Elixir's match is strict, and that strictness is a feature, because a wrong shape is caught at the exact line where it appears.

JS Stand-in: forgiving JS vs strict match

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

No output.

Where matching shows up next

You will use the same rules in many places, not just with =: in case branches, in function heads so that different shapes of argument pick different clauses (multiple clauses), in receive for messages, and in with for chains of steps that can fail. Learning the match operator well makes all of them feel familiar.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the = operator do in Elixir?

    = is the match operator. It makes the left side fit the right side and raises a MatchError if it cannot.
  2. 2. What happens with {:ok, value} = {:error, :not_found}?

    The first elements :ok and :error are different atoms, so the shapes do not fit and Elixir raises a MatchError.
  3. 3. What does the pin operator in ^expected = 6 do?

    ^ means use the existing value in the pattern. If expected is 5, then ^expected = 6 raises a MatchError.
  4. 4. Which pattern splits off the first element of a list?

    [head | tail] binds the first element to head and the remaining list to tail. [head, tail] only matches a list of exactly two elements.
  5. 5. A map pattern %{name: n} is matched against %{name: "Ana", age: 31}. What happens?

    Map patterns are partial. Extra keys in the value are ignored; only a missing pattern key causes a failure.

Summary

  • = is the match operator: it fits the left pattern to the right value and binds unbound variables.
  • Tuple and list patterns must fit exactly, except for the [head | tail] form which splits a non-empty list.
  • Map patterns are partial: extra keys are fine, missing keys fail.
  • _ ignores a part; _name is a named but unused variable.
  • A repeated variable in one pattern must match the same value; ^var matches the current value instead of rebinding.
  • A failed match raises a MatchError that shows the right-hand value.

Next: Immutability and Rebinding