Skip to content

Section 2 Lesson 17: Pattern Matching

Thiago Salles edited this page Jul 1, 2021 · 2 revisions

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

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

Notice that 1 = x is a valid expression, and it matched because both the left and right side are equal to 1. When the sides do not match, a MatchError is raised.

A variable can only be assigned on the left side of =:

iex> 1 = unknown
** (CompileError) iex:1: undefined function unknown/0

Since there is no variable unknown previously defined, Elixir assumed you were trying to call a function named unknown/0, but such a function does not exist.

The match operator is not only used to match against simple values, but it is also useful for destructuring more complex data types. For example, we can pattern match on tuples:

iex> {a, b, c} = {:hello, "world", 42}
{:hello, "world", 42}
iex> a
:hello
iex> b
"world"

I like to think that Elixir will compare if both sides have exactly the same structure and values, and if there are variables on the left side, it will try to find which values those variables need to have so the equation is valid. If possible to find those values, the variables will be assigned with them, otherwise a MatchError is raised.

The same works for the parameters of a function. It's like the definition is what comes to the left side of the equation and the received values on a call are on the right side

"Pattern Matching is Elixir's replacement for variable assignment" - Stephen Grider