Pattern Matching in Elixir

Luiz Varela
The Miners
Published in
2 min readJan 6, 2016

One of the cool things about Elixir is the pattern matching, in this post we will be able to understand about Pattern Matching and how works the pin operator “ ^”.

The pattern matching is a feature that Elixir brought from the Erlang and is a natural functional language. To make it easy see the following example:

iex> {:ok, foo} = {:ok, "hello"}
{:ok, "hello"}

In this example, we are checking if the right side matches with the pattern from the left side. From the left side, we have a tuple with an atom element and a variable called “foo”.

What Elixir does is check the type and content of the two sides, in this case, we have two tuples on the left side the first value matches the right (:ok, :ok) and the second value (foo) matches the right because we have a variable that will be filled.

The pattern matching will throw an error if the values on either side do not coincide.

iex> {a, b, c} = [:hello, "world", "!"]
** (MatchError) no match of right hand side value: [:hello, "world", "!"]

We can use pattern matching with lists:

iex> [a, b, c] = [1, 2, 3]
[1, 2, 3]
iex> a
1

Or with function definitions:

Bonus: Pattern matching with recursion.

Pin operator

The pin operator ^ should be used when you want to pattern match against an existing variable’s value rather than rebinding the variable…

So with pin operator we treat the variable like a literal value and rebind is disabled, see example:

So, in this post, I explained a little bit about pattern matching and how to use it in Elixir. The next posts I’ll show some more complex examples.

--

--