The pin operator

Variables in Elixir can be rebound:

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

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

iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {y, ^x} = {2, 1}
{2, 1}
iex> y
2
iex> {y, ^x} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

Because we have assigned the value of 1 to the variable x, this last example could also have been written as:

iex> {y, 1} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

If a variable is mentioned more than once in a pattern, all references should bind to the same pattern:

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

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.