Concurrent programming in Erlang

2.3. Expression Evaluation

Expressions have the same syntax as patterns with the addition that an expression can contain a function call or a conventional infix arithmetic expression. Func- tion calls are written conventionally, so, for example: area:triangle(A, B, C) represents calling the function area:triangle with arguments A, B and C.

The Erlang expression evaluation mechanism works as follows. Terms evaluate to themselves:

> 222.
222
> abc.
abc
> 3.1415926.
3.14159
> {a,12,[b,c|d]}.
{a,12,[b,c|d]}
> {{},[{}],{a,45,’hello world’}}.
{{},[{}],{a,45,’hello world’}}

Floating point numbers might not be printed out in exactly the same format as they were input.

Expressions evaluate to terms where the terms are isomorphic to the expressions and where each function call occurring in the expression has been evaluated. When applying a function its arguments are evaluated first.

The evaluator can be thought of as a function E which reduces an expression to a ground term:

E(X) when Constant(X) → X
E({t1,t2,...,tn}) → {E(t1),E(t2),...,E(tn)}
E([t1,t2,...,tn]) → [E(t1),E(t2),...,E(tn)]
E(functionName(t1,t2,...,tn)) →
    APPLY (functionName,[E(t1),E(t2),...,E(tn)])

where APPLY represents a function which applies a function to its arguments.

2.3.1. Evaluating functions

Function calls are written as in the following examples:

> length([a,b,c]).
3
> lists:append([a,b], [1,2,3]).
[a,b,1,2,3]
> math:pi().
3.14159

The colon form of a function is explained in the section on modules. Calls to functions with no arguments must include the empty brackets (to distinguish them from atoms).

2.3.2. Order of evaluation

The order in which the arguments to a function are evaluated is undefined. For example, f({a},b(),g(a,h(b),{f,X})) represents a function call. The function f is called with three arguments: {a}, b() and g(a,h(b),{f,X}). The first argument is a tuple of size 1 containing the atom a. The second argument is the function call b(). The third argument is the function call g(a,h(b),{f,X}). In evaluating f/3 the order of evaluation of b/0 and g/3 is undefined, though h(b) is evaluated before g/3. The order of evaluation of b() and h(b) is undefined.

When evaluating expressions such as [f(a), g(b), h(k)] the order in which f(a), g(b) and h(k) are evaluated is undefined.

If the evaluation of f(a), g(b) and h(k) has no side-effects (i.e. no messages are sent, processes spawned, etc.) then the value of [f(a), g(b), h(k)] will be the same no matter what evaluation order4 is used. This property is known as referential transparency.

2.3.3. Apply

The BIFs apply(Mod, Func, ArgList) and apply({Mod, Func}, ArgList) are functions which apply the function Func in the module Mod to the argument list ArgList.

> apply(dates, classify_day, [monday]).
weekDay
> apply(math, sqrt, [4]).
2.0
> apply({erlang, atom_to_list}, [abc]).
[97,98,99]

BIFs can be evaluated with apply by using the module name erlang.