O'Reilly logo

Erlang Programming by Francesco Cesarini, Simon Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Pattern Matching

Pattern matching in Erlang is used to:

  • Assign values to variables

  • Control the execution flow of programs

  • Extract values from compound data types

The combination of these features allows you to write concise, readable yet powerful programs, particularly when pattern matching is used to handle the arguments of a function you’re defining. A pattern match is written like this:

Pattern = Expression

And as we said earlier, it’s a generalization of what you already saw when we talked about variables.

The Pattern consists of data structures that can contain both bound and unbound variables, as well as literal values (such as atoms, integers, or strings). A bound variable is a variable which already has a value, and an unbound variable is one that has not yet been bound to a value. Examples of patterns include:

Double
{Double, 34}
{Double, Double}
[true, Double, 23, {34, Treble}]

The Expression consists of data structures, bound variables, mathematical operations, and function calls. It may not contain unbound values.

What happens when a pattern match is executed? Two results are possible:

  • The pattern match can succeed, and this results in the unbound variables becoming bound (and the value of the expression being returned).

  • The pattern match can fail, and no variables become bound as a result.

What determines whether the pattern match succeeds? The Expression on the righthand side of the = operator is first evaluated and then its value is compared to the Pattern:

  • The expression and the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required