Getting started with Erlang Language – Pattern Matching

One of the most common operations in erlang is pattern matching. It is used when assigning a value to a variable, in function declarations and in control-flow structures like case and receive statements. A pattern matching operation needs at least 2 parts: a pattern, and a term against wich the pattern is matched.

A variable assignment in erlang looks like this:

X = 2.

In most programming language the semantics of this operation is straightforward: Bind a value (2) to a name of your choice (the variable — in this case X). Erlang has a slightly different approach: Match the pattern on the left hand side (X) to the term on the right hand side (2). In this case, the effect is the same: the variable X is now bound to the value 2. However, with pattern matching you are able to perform more structured assignments.

{Type, Meta, Doc} = {document, {author, "Alice"}, {text, "Lorem Ipsum"}}.

This matching operation is performed, by analyzing the structure of the right hand side term, and applying all variables on the left hand side to the appropriate values of the term, so that the left side equals the right side. In this example Type is bound to the term: document, Meta to {author, "Alice"} and Doc to {text, "Lorem Ipsum"}. In this particular example the variables: Type, Meta and Doc are assumed to be unbound, so that each variable can be used.

Pattern matchings can also be built, using bound variables.

Identifier = error.

The variable Identifier is now bound to the value error. The following pattern matching operation works, because the structure matches, and the bound variable Identifier has the same value like the appropriate right hand side part of the term.

{Identifier, Reason} = {error, "Database connection timed out."}.

A pattern matching operation fails, when there is a mismatch between right hand side term and left hand side pattern. The following match will fail, because Identifier is bound to the value error, wich has no appropriate expression on the right hand side term.

{Identifier, Reason} = {fail, "Database connection timed out."}.
> ** exception error: no match of right hand side value {fail,"Database ..."}

if you want to reproduce, please indicate the source:
Getting started with Erlang Language – Pattern Matching - CodeDay