Pattern matching

The equals sign is not an assignment in Erlang: it is a match. The left side is a pattern, the right side is a value, and the match either binds the names in the pattern or fails. The same pattern language is used in a case, in a function head and in a receive, so learning it once covers the whole language.

The match operator

A name on the left is bound to the value it finds; a literal on the left must be equal to it. The match evaluates to the whole right side, not to true, which is why the shell prints the value again:

erl

1> Point = {1, 2}. {1,2} 2> {1, Y} = Point. {1,2} 3> Y. 2 4> X = 1, X = 1. 1

The last line is the same rule twice: the first match binds X, and the second checks it. A name that already holds a value is a pattern, not a place to store a new one, and the variables lesson builds on that.

Nested patterns

A pattern nests as deep as the data: a tuple inside a map, a list inside a tuple. The match succeeds only when every level fits, and the names at the bottom arrive bound. Deep patterns replace a chain of index reads and checks:

erl

1> {user, #{name := Who}} = {user, #{name => "Ada"}}. {user,#{name => "Ada"}} 2> Who. "Ada"

The map pattern names one key and ignores the others, so any other field of the user is allowed. This is the same rule as the maps lesson: := demands a key in a pattern, and the pattern never adds one.

Wildcards

The underscore matches anything and binds nothing, so it marks the parts a program does not need. An underscore with a name, such as _Tail, binds the value for inspection while telling the compiler that ignoring it is intended:

erl

1> {ok, _, done} = {ok, 7, done}. {ok,7,done} 2> [_, Second | _] = [1, 2, 3]. [1,2,3] 3> Second. 2

The list pattern reads the second item without naming the first or the rest. A pattern that names the same variable twice is a comparison, so {X, X} matches only a pair of equal values.

In function heads

A function head is a pattern over the arguments, and the first clause that matches runs with its variables bound. This module gives each shape of a shape its own clause:

shapes.erl

-module(shapes). -export([main/0, area/1]). area({square, Side}) -> Side * Side; area({rect, Width, Height}) -> Width * Height. main() -> io:format("~p~n", [area({square, 3})]), io:format("~p~n", [area({rect, 2, 3})]).

erlc shapes.erl

erl -noshell -eval 'shapes:main(), halt().'

9 6

The tuple's first element selects the clause, and the rest of the tuple is unpacked by the pattern, so the body has no index reads. A list head works the same way, and a base case for the empty list keeps the function total:

list_head.erl

-module(list_head). -export([main/0, first/1]). first([Head | _Tail]) -> {ok, Head}; first([]) -> empty. main() -> io:format("~p~n", [first([1, 2, 3])]), io:format("~p~n", [first([])]).

erlc list_head.erl

erl -noshell -eval 'list_head:main(), halt().'

{ok,1} empty

The two clauses are the whole function: one for a non-empty list and one for the empty one, and the order matters because the empty list is not a cons. The recursion lesson builds loops with the same pair of clauses.

When a pattern does not fit

A pattern that cannot match raises an error instead of returning false. The error is a badmatch with the value that did not fit, and it stops the process unless a try catches it:

erl

1> {error, _} = {ok, 42}. ** exception error: no match of right hand side value {ok,42}

The message carries the whole value, so the mistake is visible without a debugger. The exceptions lesson catches a badmatch, and the let it crash lesson argues for letting it stop the process. A deep pattern over a map shows the same language at work:

person.erl

-module(person). -export([main/0, city/1]). city(#{address := #{city := City}}) -> City. main() -> io:format("~s~n", [city(#{address => #{city => "Paris"}})]).

erlc person.erl

erl -noshell -eval 'person:main(), halt().'

Paris

city/1 has one clause and no error handling: a value without the two nested keys raises function_clause at the call. That is the compact way to state a contract in Erlang, and the Pattern matching in depth lesson goes on with binary patterns, as-patterns and guards.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the left side of = hold?

    Answer

    A pattern

    The match operator puts a pattern on the left and a value on the right.

  2. What does Point = {1, 2}. return?

    Answer

    {1,2}

    A successful match evaluates to the value of the right side.

  3. What does {1, Y} = {1, 2}. bind?

    Answer

    Y to 2

    The first item checks the literal 1, and the name Y receives the second item.

  4. What happens when a literal on the left does not match?

    Answer

    A badmatch exception is raised

    A pattern that cannot match the value raises an error instead of returning false.

  5. What does this module print? -module(q4). -export([main/0, same/2]). same(X, X) -> true; same(_, _) -> false. main() -> io:format("~p~n", [same(1, 2)]).

    Answer

    false

    The repeated name matches only equal values, so same(1, 2) reaches the second clause.

  6. What does the lone _ bind?

    Answer

    Nothing

    The underscore matches any value and keeps no binding.

  7. Are function heads patterns?

    Answer

    Yes, the arguments are matched clause by clause

    Each clause of a function matches its arguments, so the parts arrive already bound.

  8. What does this module print? -module(q1). -export([main/0]). main() -> {ok, Value} = {ok, 42}, io:format("~p~n", [Value]).

    Answer

    42

    The pattern binds Value to the second item, which is 42.

  9. What does this module print? -module(q2). -export([main/0]). area({square, Side}) -> Side * Side; area({rect, Width, Height}) -> Width * Height. main() -> io:format("~p~n", [area({square, 3})]).

    Answer

    9

    The {square, Side} clause matches and returns 3 * 3.

  10. What does this module print? -module(q3). -export([main/0]). main() -> [_, Second | _] = [1, 2, 3], io:format("~p~n", [Second]).

    Answer

    2

    The first item is ignored by the underscore, so Second receives 2.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev