Erlang Programming/Pattern Matching

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
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:



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

These matches fail:



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
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  variable. This variable is bound and does contain a value, however it suppresses compiler warnings regarding unused bound variables.