[Ericsson AB]

6 Expressions

In this chapter, all valid Erlang expressions are listed. When writing Erlang programs, it is also allowed to use macro- and record expressions. However, these expressions are expanded during compilation and are in that sense not true Erlang expressions. Macro- and record expressions are covered in separate chapters: Macros and Records.

6.1 Expression Evaluation

All subexpressions are evaluated before an expression itself is evaluated, unless explicitly stated otherwise. For example, consider the expression:

Expr1 + Expr2
    

Expr1 and Expr2, which are also expressions, are evaluated first - in any order - before the addition is performed.

Many of the operators can only be applied to arguments of a certain type. For example, arithmetic operators can only be applied to numbers. An argument of the wrong type will cause a badarg run-time error.

6.2 Terms

The simplest form of expression is a term, that is an integer, float, atom, string, list or tuple. The return value is the term itself.

6.3 Variables

A variable is an expression. If a variable is bound to a value, the return value is this value. Unbound variables are only allowed in patterns.

Variables start with an uppercase letter or underscore (_) and may contain alphanumeric characters, underscore and @. Examples:

X
Name1
PhoneNumber
Phone_number
_
_Height
    

Variables are bound to values using pattern matching. Erlang uses single assignment, a variable can only be bound once.

The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored. Example:

[H|_] = [1,2,3]
    

Variables starting with underscore (_), for example _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they will not generate any warnings for unused variables. Example: The following code

member(_, []) ->
    [].
    

can be rewritten to be more readable:

member(Elem, []) ->
    [].
    

This will however cause a warning for an unused variable Elem, if the code is compiled with the flag warn_unused_vars set. Instead, the code can be rewritten to:

member(_Elem, []) ->
    [].
    

Note that since variables starting with an underscore are not anonymous, this will match:

{_,_} = {1,2}
    

But this will fail:

{_N,_N} = {1,2}
    

The scope for a variable is its function clause. Variables bound in a branch of an if, case, or receive expression must be bound in all branches to have a value outside the expression, otherwise they will be regarded as 'unsafe' outside the expression.

For the try expression introduced in Erlang 5.4/OTP-R10B, variable scoping is limited so that variables bound in the expression are always 'unsafe' outside the expression. This will be improved.

6.4 Patterns

A pattern has the same structure as a term but may contain unbound variables. Example:

Name1
[H|T]
{error,Reason}
    

Patterns are allowed in clause heads, case and receive expressions, and match expressions.

6.4.1 Match Operator = in Patterns

If Pattern1 and Pattern2 are valid patterns, then the following is also a valid pattern:

Pattern1 = Pattern2
      

When matched against a term, both Pattern1 and Pattern2 will be matched against the term. The idea behind this feature is to avoid reconstruction of terms. Example:

f({connect,From,To,Number,Options}, To) ->
    Signal = {connect,From,To,Number,Options},
    ...;
f(Signal, To) ->
    ignore.
      

can instead be written as

f({connect,_,To,_,_} = Signal, To) ->
    ...;
f(Signal, To) ->
    ignore.
      

6.4.2 String Prefix in Patterns

When matching strings, the following is a valid pattern:

f("prefix" ++ Str) -> ...
      

This is syntactic sugar for the equivalent, but harder to read

f([$p,$r,$e,$f,$i,$x | Str]) -> ...
      

6.4.3 Expressions in Patterns

An arithmetic expression can be used within a pattern, if it uses only numeric or bitwise operators, and if its value can be evaluated to a constant at compile-time. Example:

case {Value, Result} of
    {?THRESHOLD+1, ok} -> ...
      

This feature was added in Erlang 5.0/OTP R7.

6.5 Match

Expr1 = Expr2
    

Matches Expr1, a pattern, against Expr2. If the matching succeeds, any unbound variable in the pattern becomes bound and the value of Expr2 is returned.

If the matching fails, a badmatch run-time error will occur.

Examples:

1> {A, B} = {answer, 42}.
{answer,42}
2> A.
answer
3> {C, D} = [1, 2].
** exited: {{badmatch,[1,2]},[{erl_eval,expr,3}]} **
    

6.6 Function Calls

ExprF(Expr1,...,ExprN)
ExprM:ExprF(Expr1,...,ExprN)
    

ExprM should evalutate to a module name and ExprF to a function name or a fun.

When including the module name, the function is said to be called by using the fully qualified function name. This is often referred to as a remote or external function call. Example:

lists:keysearch(Name, 1, List)
    

The module name can be omitted, if ExprF evaluates to the name of a local function, an imported function, or an auto-imported BIF. Then the function is said to be called by using the implicitly qualified function name. Examples:

handle(Msg, State)
spawn(m, init, [])
    

To avoid possible ambiguities, the fully qualified function name must be used when calling a function with the same name as a BIF, and the compiler does not allow defining a function with the same name as an imported function.

Note that when calling a local function, there is a difference between using the implicitly or fully qualified function name, as the latter always refer to the latest version of the module. See Compilation and Code Loading.

If ExprF evaluates to a fun, only the format ExprF(Expr1,...,ExprN) is correct. Example:

Fun1 = fun(X) -> X+1 end
Fun1(3)
=> 4

Fun2 = {lists,append}
Fun2([1,2],[3,4])
=> [1,2,3,4]
    

See also the chapter about Function Evaluation.

6.7 If

if
    GuardSeq1 ->
        Body1;
    ...;
    GuardSeqN ->
        BodyN
end
    

The branches of an if-expression are scanned sequentially until a guard sequence GuardSeq which evaluates to true is found. Then the corresponding Body (sequence of expressions separated by ',') is evaluated.

The return value of Body is the return value of the if expression.

If no guard sequence is true, an if_clause run-time error will occur. If necessary, the guard expression true can be used in the last branch, as that guard sequence is always true.

Example:

is_greater_than(X, Y) ->
    if
        X>Y ->
            true;
        true -> % works as an 'else' branch
            false
    end
    

6.8 Case

case Expr of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
end
    

The expression Expr is evaluated and the patterns Pattern are sequentially matched against the result. If a match succeeds and the optional guard sequence GuardSeq is true, the corresponding Body is evaluated.

The return value of Body is the return value of the case expression.

If there is no matching pattern with a true guard sequence, a case_clause run-time error will occur.

Example:

is_valid_signal(Signal) ->
    case Signal of
        {signal, _What, _From, _To} ->
            true;
        {signal, _What, _To} ->
            true;
        _Else ->
            false
    end.
    

6.9 Send

Expr1 ! Expr2
    

Sends the value of Expr2 as a message to the process specified by Expr1. The value of Expr2 is also the return value of the expression.

Expr1 must evaluate to a pid, a registered name (atom) or a tuple {Name,Node}, where Name is an atom and Node a node name, also an atom.

6.10 Receive

receive
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
end
    

Receives messages sent to the process using the send operator (!). The patterns Pattern are sequentially matched against the first message in time order in the mailbox, then the second, and so on. If a match succeeds and the optional guard sequence GuardSeq is true, the corresponding Body is evaluated. The matching message is consumed, that is removed from the mailbox, while any other messages in the mailbox remain unchanged.

The return value of Body is the return value of the receive expression.

receive never fails. Execution is suspended, possibly indefinitely, until a message arrives that does match one of the patterns and with a true guard sequence.

Example:

wait_for_onhook() ->
    receive
        onhook ->
            disconnect(),
            idle();
        {connect, B} ->
            B ! {busy, self()},
            wait_for_onhook()
    end.
    

It is possible to augment the receive expression with a timeout:

receive
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
after
    ExprT ->
        BodyT
end
    

ExprT should evaluate to an integer. The highest allowed value is 16#ffffffff, that is, the value must fit in 32 bits. receive..after works exactly as receive, except that if no matching message has arrived within ExprT milliseconds, then BodyT is evaluated instead and its return value becomes the return value of the receive..after expression.

Example:

wait_for_onhook() ->
    receive
        onhook ->
            disconnect(),
            idle();
        {connect, B} ->
            B ! {busy, self()},
            wait_for_onhook()
    after
        60000 ->
            disconnect(),
            error()
    end.
    

It is legal to use a receive..after expression with no branches:

receive
after
    ExprT ->
        BodyT
end
    

This construction will not consume any messages, only suspend execution in the process for ExprT milliseconds and can be used to implement simple timers.

Example:

timer() ->
    spawn(m, timer, [self()]).

timer(Pid) ->
    receive
    after
        5000 ->
            Pid ! timeout
    end.
    

There are two special cases for the timeout value ExprT:

infinity
The process should wait indefinitely for a matching message -- this is the same as not using a timeout. Can be useful for timeout values that are calculated at run-time.
0
If there is no matching message in the mailbox, the timeout will occur immediately.

6.11 Term Comparisons

Expr1 op Expr2
    

Term Comparison Operators.
op Description
== equal to
/= not equal to
=< less than or equal to
< less than
>= greater than or equal to
> greater than
=:= exactly equal to
=/= exactly not equal to

The arguments may be of different data types. The following order is defined:

number < atom < reference < fun < port < pid < tuple < list < binary
    

Lists are compared element by element. Tuples are ordered by size, two tuples with the same size are compared element by element.

All comparison operators except =:= and =/= are of type coerce: When comparing an integer and a float, the integer is first converted to a float. In the case of =:= and =/=, there is no type conversion.

Returns the Boolean value of the expression, true or false.

Examples:

1> 1==1.0.
true
2> 1=:=1.0.
false
3> 1 > a.
false
    

6.12 Arithmetic Expressions

op Expr
Expr1 op Expr2
    

Arithmetic Operators.
op Description Argument type
+ unary + number
- unary - number
+   number
-   number
*   number
/ floating point division number
bnot unary bitwise not integer
div integer division integer
rem integer remainder of X/Y integer
band bitwise and integer
bor bitwise or integer
bxor arithmetic bitwise xor integer
bsl arithmetic bitshift left integer
bsr bitshift right integer

Examples:

1> +1.
1
2> -1.
-1
3> 1+1.
2
4> 4/2.
2.00000
5> 5 div 2.
2
6> 5 rem 2.
1
7> 2#10 band 2#01.
0
8> 2#10 bor 2#01.
3
    

6.13 Boolean Expressions

op Expr
Expr1 op Expr2
    

Logical Operators.
op Description
not unary logical not
and logical and
or logical or
xor logical xor

Examples:

1> not true.
false
2> true and false.
false
3> true xor false.
true
    

6.14 Short-Circuit Boolean Expressions

Expr1 orelse Expr2
Expr1 andalso Expr2
    

Boolean expressions where Expr2 is evaluated only if necessary. That is, Expr2 is evaluated only if Expr1 evaluates to false in an orelse expression, or only if Expr1 evaluates to true in an andalso expression. Returns the Boolean value of the expression, that is true or false.

As of Erlang 5.5/OTP R11B, short-circuit boolean expressions are allowed in guards. In guards, however, evaluation is always short-circuited since guard tests are known to be free of side effects.

Example 1:

case A >= -1.0 andalso math:sqrt(A+1) > B of
    

This will work even if A is less than -1.0, since in that case, math:sqrt/1 is never evaluated.

Example 2:

OnlyOne = is_atom(L) orelse
         (is_list(L) andalso length(L) == 1),
    

This feature was added in Erlang 5.1/OTP R8.

6.15 List Operations

Expr1 ++ Expr2
Expr1 -- Expr2
    

The list concatenation operator ++ appends its second argument to its first and returns the resulting list.

The list subtraction operator -- produces a list which is a copy of the first argument, subjected to the following procedure: for each element in the second argument, the first occurrence of this element (if any) is removed.

Example:

1> [1,2,3]++[4,5].
[1,2,3,4,5]
2> [1,2,3,2,1,2]--[2,1,2].
[3,1,2]
    

6.16 Bit Syntax Expressions

<<>>
<<E1,...,En>>
    

Each element Ei specifies a segment of the binary. Each element Ei is a value, followed by an optional size expression and an optional type specifier list.

Ei = Value |
     Value:Size |
     Value/TypeSpecifierList |
     Value:Size/TypeSpecifierList
    

Used in a binary construction, Value is an expression which should evaluate to an integer, float or binary. If the expression is something else than a single literal or variable, it should be enclosed in parenthesis.

Used in a binary matching, Value must be a variable, or an integer, float or string.

Note that, for example, using a string literal as in <<"abc">> is syntactic sugar for <<$a,$b,$c>>.

Used in a binary construction, Size is an expression similar to Value, which should evaluate to an integer.

Used in a binary matching, Size must be an integer, or a variable bound to an integer.

The value of Size specifies the size of the segment in units (see below). The default value depends on the type (see below). For integer it is 8, for float it is 64, for binary it is all of the binary. In matching, this default value is only valid for the very last element. All other binary elements in the matching must have a size specification.

TypeSpecifierList is a list of type specifiers, in any order, separated by hyphens (-). Default values are used for any omitted type specifiers.

Type = integer | float | binary
The default is integer.
Signedness = signed | unsigned
Only matters for matching. The default is unsigned.
Endianness = big | little | native
Native-endian means that the endian will be resolved at load time to be either big-endian or little-endian, depending on what is native for the CPU that the Erlang machine is run on. The default is big.
Unit = unit:IntegerLiteral
The allowed range is 1..256. Defaults to 1 for integer and float, and to 8 for binary.

The value of Size multiplied with the unit gives the number of bits for the segment. Each segment can consist of zero or more bits, but the total number of bits must be divisible by 8, or a badarg run-time error will occur. Also, a segment of type binary must have a size evenly divisble by 8.

Examples:

1> Bin1 = <<1,17,42>>.
<<1,17,42>>
2> Bin2 = <<"abc">>.
<<97,98,99>>
3> Bin3 = <<1,17,42:16>>.
<<1,17,0,42>>
4> <<A,B,C:16>> = <<1,17,42:16>>.
<<1,17,0,42>>
5> C.
42
6> <<D:16,E,F>> = <<1,17,42:16>>.
<<1,17,0,42>>
7> D.
273
8> F.
42
9> <<G,H/binary>> = <<1,17,42:16>>.
<<1,17,0,42>>
10> H.
<<17,0,42>>
    

Note that binary patterns cannot be nested.

Note also that "B=<<1>>" is interpreted as "B =< <1>>" which is a syntax error. The correct way is to write a space after '=': "B= <<1>>.

More examples can be found in Programming Examples.

6.17 Fun Expressions

fun
    (Pattern11,...,Pattern1N) [when GuardSeq1] ->
        Body1;
    ...;
    (PatternK1,...,PatternKN) [when GuardSeqK] ->
        BodyK
end
    

A fun expression begins with the keyword fun and ends with the keyword end. Between them should be a function declaration, similar to a regular function declaration, except that no function name is specified.

Variables in a fun head shadow variables in the function clause surrounding the fun expression, and variables bound in a fun body are local to the fun body.

The return value of the expression is the resulting fun.

Examples:

1> Fun1 = fun (X) -> X+1 end.
#Fun<erl_eval.6.39074546>
2> Fun1(2).
3
3> Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.
#Fun<erl_eval.6.39074546>
4> Fun2(7).
gt
    

The following fun expressions are also allowed:

fun Name/Arity
fun Module:Name/Arity
    

In Name/Arity, Name is an atom and Arity is an integer. Name/Arity must specify an existing local function. The expression is syntactic sugar for:

fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end
    

In Module:Name/Arity, Module and Name are atoms and Arity is an integer. A fun defined in this way will refer to the function Name with arity Arity in the latest version of module Module.

When applied to a number N of arguments, a tuple {Module,FunctionName} is interpreted as a fun, referring to the function FunctionName with arity N in the module Module. The function must be exported. This usage is deprecated. See Function Calls for an example.

More examples can be found in Programming Examples.

6.18 Catch and Throw

catch Expr
    

Returns the value of Expr unless an exception occurs during the evaluation. In that case, the exception is caught. For exceptions of class error, that is run-time errors: {'EXIT',{Reason,Stack}} is returned. For exceptions of class exit, that is the code called exit(Term): {'EXIT',Term} is returned. For exceptions of class throw, that is the code called throw(Term): Term is returned.

Reason depends on the type of error that occurred, and Stack is the stack of recent function calls, see Errors and Error Handling.

Examples:

1> catch 1+2.
3
2> catch 1+a.
{'EXIT',{badarith,[...]}}
    

Note that catch has low precedence and catch subexpressions often needs to be enclosed in a block expression or in parenthesis:

3> A = catch 1+2.
** 1: syntax error before: 'catch' **
4> A = (catch 1+2).
3
    

The BIF throw(Any) can be used for non-local return from a function. It must be evaluated within a catch, which will return the value Any. Example:

5> catch throw(hello).
hello
    

If throw/1 is not evaluated within a catch, a nocatch run-time error will occur.

6.19 Try

try Expr
catch
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
        ExceptionBody1;
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
        ExceptionBodyN
end
    

This is an enhancement of catch that appeared in Erlang 5.4/OTP-R10B. It gives the possibility do distinguish between different exception classes, and to choose to handle only the desired ones, passing the others on to an enclosing try or catch or to default error handling.

Note that althought the keyword catch is used in the try expression there is not a catch expression whithin the try expression.

Returns the value of Expr unless an exception occurs during the evaluation. In that case the exception is caught and the patterns ExceptionPattern with the right exception class Class are sequentially matched against the caught exception. An omitted Class is shorthand for throw. If a match succeeds and the optional guard sequence ExceptionGuardSeq is true, the corresponding ExceptionBody is evaluated to become the return value.

If an exception occurs during evaluation of Expr but there is no matching ExceptionPattern of the right Class with a true guard sequence, the exception is passed on as if Expr had not been enclosed in a try expression.

If an exception occurs during evaluation of ExceptionBody it is not caught.

The try expression can have an of section:

try Expr of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
catch
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
        ExceptionBody1;
    ...;
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
        ExceptionBodyN
end
    

If the evaluation of Expr succedes without an exception, the value is then matched against the patterns Pattern in the same way as for a case expression to produce the return value, except that if the matching fails, a try_clause run-time error will occur.

If an exception occurs during evaluation of Body it is not caught.

The try expression can also be augumented with an after section, intended to be used for cleanup with side effects:

try Expr of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
catch
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
        ExceptionBody1;
    ...;
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
        ExceptionBodyN
after
    AfterBody
end
    

The AfterBody is evaluated after either Body or ExceptionBody no matter which one. The evaluated value of the AfterBody is lost; the return value of the try expression is the same with an after section as without.

Even if an exception occurs during evaluation of Body or ExceptionBody, the AfterBody is evaluated. In this case the exception is caught and passed on after the AfterBody has been evaluated, so the exception from the try expression is the same with an after section as without.

If an exception occurs during evaluation of AfterBody itself it is not caught, so if the AfterBody is evaluated due to an exception in Expr, Body or ExceptionBody, that exception is lost and masked by the new exception.

The of, catch and after sections, are all optional in the try expression, as long as there is at least a catch or an after section, so the following are also valid try expressions:

try Expr of 
    Pattern when GuardSeq -> 
        Body 
after 
    AfterBody 
end

try Expr 
catch 
    ExpressionPattern -> 
        ExpressionBody
after
    AfterBody
end

try Expr after AfterBody end

Example of using after, this code will close the file even in the event of exceptions in file:read/2 or in binary_to_term/1, and exceptions will be the same as without the try...after...end expression:

termize_file(Name) ->
    {ok,F} = file:open(Name, [read,binary]),
    try
        {ok,Bin} = file:read(F, 1024*1024),
        binary_to_term(Bin)
    after
        file:close(F)
    end.

Example: Using try to emulate catch Expr

try Expr
catch
    throw:Term -> Term;
    exit:Reason -> {'EXIT',Reason}
    error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}}
end

6.20 Parenthesized Expressions

(Expr)
    

Parenthesized expressions are useful to override operator precedences, for example in arithmethic expressions:

1> 1 + 2 * 3.
7
2> (1 + 2) * 3.
9
    

6.21 Block Expressions

begin
   Expr1,
   ...,
   ExprN
end
    

Block expressions provide a way to group a sequence of expressions, similar to a clause body. The return value is the value of the last expression ExprN.

6.22 List Comprehensions

List comprehensions are a feature of many modern functional programming languages. Subject to certain rules, they provide a succinct notation for generating elements in a list.

List comprehensions are analogous to set comprehensions in Zermelo-Frankel set theory and are called ZF expressions in Miranda. They are analogous to the setof and findall predicates in Prolog.

List comprehensions are written with the following syntax:

[Expr || Qualifier1,...,QualifierN]
    

Expr is an arbitrary expression, and each Qualifier is either a generator or a filter.

The variables in the generator patterns shadow variables in the function clause surrounding the list comprehensions.

A list comprehension returns a list, where the elements are the result of evaluating Expr for each combination of generator list elements for which all filters are true.

Example:

1> [X*2 || X <- [1,2,3]].
[2,4,6]
    

More examples can be found in Programming Examples.

6.23 Guard Sequences

A guard sequence is a sequence of guards, separated by semicolon (;). The guard sequence is true if at least one of the guards is true.
Guard1;...;GuardK

A guard is a sequence of guard expressions, separated by comma (,). The guard is true if all guard expressions evaluate to true.
GuardExpr1,...,GuardExprN

The set of valid guard expressions (sometimes called guard tests) is a subset of the set of valid Erlang expressions. The reason for restricting the set of valid expressions is that evaluation of a guard expression must be guaranteed to be free of side effects. Valid guard expressions are:

Type Test BIFs.
is_atom/1
is_binary/1
is_constant/1
is_float/1
is_function/1
is_function/2
is_integer/1
is_list/1
is_number/1
is_pid/1
is_port/1
is_reference/1
is_tuple/1
is_record/2
is_record/3

Note that each type test BIF has an older equivalent, without the is_ prefix. These old BIFs are retained for backwards compatibility only and should not be used in new code. They are also only allowed at top level. For example, they are not allowed in boolean expressions in guards.

Other BIFs Allowed in Guard Expressions.
abs(Number)
element(N, Tuple)
float(Term)
hd(List)
length(List)
node()
node(Pid|Ref|Port)
round(Number)
self()
size(Tuple|Binary)
tl(List)
trunc(Number)

6.24 Operator Precedence

Operator precedence in falling priority:

Operator Precedence.
:  
#  
Unary + - bnot not  
/ * div rem band and Left associative
+ - bor bxor bsl bsr or xor Left associative
++ -- Right associative
== /= =< < >= > =:= =/= -
andalso  
orelse  
= ! Right associative
catch  

When evaluating an expression, the operator with the highest priority is evaluated first. Operators with the same priority are evaluated according to their associativity. Example: The left associative arithmethic operators are evaluated left to right:

6 + 5 * 4 - 3 / 2 evaluates to
6 + 20 - 1.5 evaluates to
26 - 1.5 evaluates to
24.5
    

Copyright © 1991-2006 Ericsson AB