Concurrent programming in Erlang

1.3.  Pattern Matching

Pattern matching is used for assigning values to variables and for controlling the flow of a program. Erlang is a single assignment language, which means that once a variable has been assigned a value, the value can never be changed.

Pattern matching is used to match patterns with terms. If a pattern and term have the same shape then the match will succeed and any variables occurring in the pattern will be bound to the data structures which occur in the corresponding positions in the term.

1.3.1. Pattern matching when calling a function

Program 1.4 defines the function convert which is used to convert temperatures be- tween the Celsius, Fahrenheit and Re ́aumur scales. The first argument to convert is a tuple containing the scale and value of the temperature to be converted and the second argument is the scale to which we wish to convert.

-module(temp).
-export([convert/2]).

convert({fahrenheit, Temp}, celsius) ->
        {celsius, 5 * (Temp - 32) / 9};
convert({celsius, Temp}, fahrenheit) ->
        {farenheit, 32 + Temp * 9 / 5};
convert({reaumur, Temp}, celsius) ->
        {celsius, 10 * Temp / 8};
convert({celsius, Temp}, reaumur) ->
        {reaumur, 8 * Temp / 10};
convert({X, _}, Y) ->
        {cannot,convert,X,to,Y}.

When convert is evaluated, the arguments occurring in the function call (terms) are matched against the patterns occurring in the function definition. When a match occurs the code following the -> symbol is evaluated, so:

> temp:convert({fahrenheit, 98.6}, celsius).
{celsius,37.0000}
> temp:convert({reaumur, 80}, celsius).
{celsius,100.000}
> temp:convert({reaumur, 80}, fahrenheit).
{cannot,convert,reaumur,to,fahrenheit}

1.3.2. The match primitive =

The expression Pattern = Expression causes Expression to be evaluated and the result matched against Pattern. The match either succeeds or fails. If the match succeeds any variables occurring in Pattern become bound, for example:

> N = {12, banana}.
{12,banana}
> {A, B} = N.
{12,banana}
> A.
12
> B.
banana

The match primitive can be used to unpack items from complex data structures:

> {A, B} = {[1,2,3], {x,y}}.
{[1,2,3],{x,y}}
> A.
[1,2,3]
> B.
{x,y}
> [a,X,b,Y] = [a,{hello, fred},b,1].
[a,{hello,fred},b,1]
> X.
{hello,fred}
> Y.
1
> {_,L,_} = {fred,{likes, [wine, women, song]},
  {drinks, [whisky, beer]}}.
{fred,{likes,[wine,women,song]},{drinks,[whisky,beer]}}
> L.
{likes,[wine,women,song]}

The special variable underscore (written _) is the anonymous or don't care variable. It is used as a place holder where the syntax requires a variable, but the value of the variable is of no interest.

If the match succeeds, the value of the expression Lhs = Rhs is defined to be Rhs. This allows multiple uses of match within a single expression, for example:

{A, B} = {X, Y} = C = g(a, 12)

= is regarded as an infix right associative operator; thus A = B = C = D is parsed as A = (B = (C = D)).