Jump to content

Erlang Programming/Pattern Matching

From Wikibooks, open books for an open world

← Terms | Expressions →

Erlang uses powerful pattern-matching to bind variables to values. Pattern matching can be explicit, as when the = (pattern matching operator) is used, or implicit, as when a function call is processed and a function's actual arguments are matched with its formal parameters.

Patterns

[edit | edit source]

Patterns look the same as terms - they can be simple literals like atoms and numbers, compound like tuples and lists, or a mixture of both. They can also contain variables, which are alphanumeric strings that begin with a capital letter or underscore. A special "anonymous variable", _ (the underscore) is used when you don't care about the value to be matched, and won't be using it.

A pattern matches if it has the same "shape" as the term being matched, and atoms encountered are the same. For example, the following matches succeed:[1]

  • A = 1.
  • 1 = 1.
  • {ok, A} = {ok, 42}.
  • [H|T] = [1, 2, 3].

Note that in the fourth example, the pipe (|) signifying the head and tail of the list as described in Terms.

These matches fail:

  • 1 = 2.
  • {ok, A} = {failure, "Don't know the question"}.
  • [H|T] = [].

In the case of the pattern-matching operator, a failure generates an error and the process exits. How this can be trapped and handled is covered in Errors.

Patterns are used to select which clause of a function will be executed (this is covered in Functions; which option to select in a case expression (Expressions); and which messages to retrieve from the mailbox (Processes).

Variables

[edit | edit source]

Erlang variables are single-assignment variables that do not have to be declared. They are written with a capital letter or underscore followed by an alphanumeric sequence. They are bound to values using the pattern matching mechanism. The Erlang compiler will produce an error if an unbound variable is used, and a warning if a bound variable is not used. Sometimes you might encounter a _Var variable. This variable is bound and does contain a value, however it suppresses compiler warnings regarding unused bound variables.

Notes

[edit | edit source]
  1. Since Erlang variables are immutable, consider examples like this to be standalone--even though the A is used twice, it's a different A each time!