Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Functions and Pattern Matching

Pattern Matching in Erlang

Master Erlang pattern matching: match tuples, lists, maps and strings in function heads, case and receive, bind variables and use the common ok/error idiom.

Pattern matching is the single most important feature of Erlang. You use it to take data apart, to choose between clauses, to check results and to receive messages. Once it clicks, your code gets shorter and the "if" statements disappear.

What a pattern is

A pattern looks like a term, but it may contain unbound variables. Matching compares the pattern against a value: constants must be equal, and each unbound variable is bound to the corresponding part of the value. If the shapes differ, the match fails.

ERLANG
1> {point, X, Y} = {point, 3, 4}.
{point,3,4}
2> X.
3
3> Y.
4
4> {point, X2, Y2} = {circle, 3, 4}.
** exception error: no match of right hand side value {circle,3,4}

point is an atom, so it must match exactly; X and Y are free and receive 3 and 4. In the fourth line the atoms differ, so the match fails. Patterns can be nested as deeply as you like:

ERLANG
1> {user, Name, {address, City, _}} = {user, "Ada", {address, "London", "UK"}}.
{user,"Ada",{address,"London","UK"}}
2> City.
"London"

Matching lists

A list pattern [Head | Tail] splits the first element from the rest. This is the basis of almost all list processing:

ERLANG
1> [H | T] = [1, 2, 3].
[1,2,3]
2> H.
1
3> T.
[2,3]
4> [A, B | Rest] = [10, 20, 30, 40].
[10,20,30,40]
5> Rest.
[30,40]
6> [X] = [only].
[only]
7> [] = [].
[]

The pattern [H | T] does not match the empty list, which is how recursive functions detect the end. See recursion.

Matching in function heads

This is where pattern matching shines. Each clause is a pattern for the arguments:

ERLANG
-module(shape).
-export([area/1, describe/1]).

area({square, Side}) -> Side * Side;
area({rectangle, W, H}) -> W * H;
area({circle, R}) -> math:pi() * R * R.

describe([]) -> "empty";
describe([_]) -> "one element";
describe([_, _]) -> "two elements";
describe([_, _, _ | _]) -> "three or more".
ERLANG
1> shape:area({rectangle, 3, 4}).
12
2> shape:describe([a, b, c, d]).
"three or more"

You do not need if or a type field: the shape of the data is the type. A function that handles the cases explicitly is easy to read and to extend.

The ok/error idiom

Many Erlang functions return {ok, Value} on success and {error, Reason} on failure. Matching distinguishes them:

ERLANG
case file:read_file("data.txt") of
    {ok, Binary} -> process(Binary);
    {error, enoent} -> io:format("file not found~n");
    {error, Reason} -> io:format("failed: ~p~n", [Reason])
end

If you expect success and want a crash otherwise, write {ok, Binary} = file:read_file("data.txt"). A failing match crashes the process, and a supervisor decides what to do.

Matching strings, maps and binaries

Strings are lists, so a string prefix matches like any list:

ERLANG
command("get " ++ Key) -> {get, Key};
command("set " ++ Rest) -> {set, Rest};
command(_) -> unknown.

"get " ++ Key is a legal pattern because the left side of ++ is a literal. Maps match by key subset:

ERLANG
1> #{name := Name} = #{name => "Ada", age => 36}.
#{age => 36,name => "Ada"}
2> Name.
"Ada"

In map patterns use :=, not =>. The pattern requires name to exist and ignores other keys. Binaries match with bit syntax, for example <<"HTTP/", Rest/binary>>; see binaries.

Matching with an already bound variable

If a variable is already bound, it acts as a constant. Use this to test equality or to build a selective receive:

ERLANG
Expected = 5,
{value, Expected} = {value, 5},     % ok, 5 =:= 5
{value, Expected} = {value, 6}.     % badmatch

For function heads this means a repeated variable demands equal values:

ERLANG
same(X, X) -> true;
same(_, _) -> false.

Aliasing with =

A pattern can bind the whole value and its parts at once using = inside the pattern:

ERLANG
print_first([First | _] = List) ->
    io:format("first ~p of ~p~n", [First, List]).

List and First are both bound. This avoids rebuilding the list.

What cannot be a pattern

Function calls and arbitrary operators cannot appear in a pattern, with a few exceptions: the compile-time arithmetic of constants and the string prefix "abc" ++ Rest. To compare against a computed value, bind it first or use a guard.

A match that fails in a function head is not an error by itself; the runtime just tries the next clause. Only when all clauses fail does the call raise function_clause.

A stand-in matcher

This JavaScript code is a small pattern matcher for tuples and lists. It is not Erlang: real matching is built into the VM.

JS Stand-in: a tiny pattern matcher (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: head and tail of a list (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when {ok, V} = {error, nope} is evaluated?

    The atoms ok and error differ, so the match fails and raises badmatch.
  2. 2. Which pattern matches a list with at least one element and binds its first element?

    [H | T] splits the head from the tail and fails on the empty list.
  3. 3. How does a map pattern require a key?

    In patterns use := to match an existing key; => is for creating or updating maps.
  4. 4. What does same(X, X) -> true; same(_, _) -> false. test?

    A variable repeated in a head must match equal values in both places.

Summary

  • A pattern is a term with variables; matching binds them or fails.
  • Use patterns in =, function heads, case and receive.
  • [H | T] splits a list; it does not match [].
  • {ok, V} / {error, R} results are told apart by matching.
  • A bound variable acts as a constant; a repeated variable requires equal values.

Next: case, if and Guards