Pattern Matching in Elixir: Five Things to Remember

Урок 2. Сопоставление с образцом

there is no assignment

In Elixir there is no assignment: the = is a match operator.

iex(1)> a=1
1
iex(2)> a
1

It looks like a generic assignment in most languages, but this is matching: there is a pattern with variables in required places, which matches with data structure, and variables will be bound to corresponding subelements of these data.

iex(8)> [a,_,b]=[1,2,3]  
[1, 2, 3]
iex(9)> a
1
iex(10)> b
3

_ ignore placeholders

The _ placeholders mark parts of data, which are not needed.

iex(12)> 3=b
3
iex(13)> 4=b
** (MatchError) no match of right hand side value: 3

It matches because b was already bounded to 3. and 3=3.

^ pin prefix operator

iex(13)> a=1
1
iex(14)> a=2
2
iex(15)> a=1
1
iex(16)> ^a=1
1
iex(17)> ^a=2
** (MatchError) no match of right hand side value: 2

The ^ pin operator used as a prefix in the left side blocks variable binding while matching.

As a result, any pinned variable in the left will not be (re)bound with new value.

data structure matching

The same way matching does with basic data structures:

iex(17)> [a,b]=[1,2]
[1, 2]
iex(18)> a
1
iex(19)> b
2