Pattern matching.

In this chapter, we will show how the = operator in Elixir is actually a match operator and how to use it to pattern match inside data structures. Finally, we will learn about the pin operator ^ used to access previously bound values.

The match operator

We have used the = operator a couple times to assign variables in Elixir:

iex> x = 1
1
iex> x
1

In Elixir, the = operator is actually called the match operator. Let’s see why:

The [head | tail] format is not only used on pattern matching but also for prepending items to a list:

iex> list = [1, 2, 3]
[1, 2, 3]
iex> [0 | list]
[0, 1, 2, 3]

Pattern matching allows developers to easily destructure data types such as tuples and lists. As we will see in the following chapters, it is one of the foundations of recursion in Elixir and applies to other types as well, like maps and binaries.

The pin operator

Variables in Elixir can be rebound:

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

Use the pin operator ^ when you want to pattern match against an existing variable’s value rather than rebinding the variable:

In some cases, you don’t care about a particular value in a pattern. It is a common practice to bind those values to the underscore, _. For example, if only the head of the list matters to us, we can assign the tail to underscore:

iex> [h | _] = [1, 2, 3]
[1, 2, 3]
iex> h
1

The variable _ is special in that it can never be read from. Trying to read from it gives an unbound variable error:

iex> _
** (CompileError) iex:1: unbound variable _

Although pattern matching allows us to build powerful constructs, its usage is limited. For instance, you cannot make function calls on the left side of a match. The following example is invalid:

iex> length([1, [2], 3]) = 3
** (CompileError) iex:1: illegal pattern

This finishes our introduction to pattern matching. As we will see in the next chapter, pattern matching is very common in many language constructs.