Pattern matching
| The match operator | |
| Nested patterns | |
| Wildcards | |
| In function heads |
The match operator
The equals sign matches the left pattern against the right value. When the left side holds names, it binds them; when it holds literals, it checks them.
This one operator is the backbone of the language: assignment, argument passing, and case branches are all matches.
Point = {1, 2}.
{1,2}
2> {1, Y} = Point.
{1,2}
3> Y.
2
Nested patterns
Patterns nest as deep as your data: a tuple inside a list inside a map. The match succeeds only when every level lines up.
Deep patterns replace whole chains of index reads and if tests in other languages.
{user, #{name := Who}} = {user, #{name => "Ada"}}.
{user,#{name => "Ada"}}
2> Who.
"Ada"
Wildcards
The underscore matches anything and binds nothing. It marks the parts of the data you do not need.
An underscore with a name binds the value for inspection while telling the compiler you plan to ignore it.
{ok, _, done} = {ok, 7, done}.
{ok,7,done}
2> [_, Second | _] = [1, 2, 3].
[1,2,3]
3> Second.
2
In function heads
Function heads are patterns too. Each clause matches its arguments in order, so the first clause that fits runs with the matched parts already bound.
This is why Erlang code so often has no explicit assignment at all: the arguments arrive already unpacked.
area({square, S}) -> S * S;
area({rect, W, H}) -> W * H.
1> area({square, 3}).
9
Next: Guards
Article author: Arthur Isaev