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:
All subexpressions are evaluated before an expression itself is evaluated, unless explicitly stated otherwise. For example, consider the expression:
Expr1 + Expr2
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
The simplest form of expression is a term, that is an integer, float, atom, string, list, map or tuple. The return value is the term itself.
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
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
member(_, []) -> [].
can be rewritten to be more readable:
member(Elem, []) -> [].
This will however cause a warning for an unused variable
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
For the
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,
If
Pattern1 = Pattern2
When matched against a term, both
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.
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]) -> ...
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.
Expr1 = Expr2
Matches
If the matching fails, a
Examples:
1> {A, B} = {answer, 42}. {answer,42} 2> A. answer 3> {C, D} = [1, 2]. ** exception error: no match of right hand side value [1,2]
ExprF(Expr1,...,ExprN) ExprM:ExprF(Expr1,...,ExprN)
In the first form of function calls,
lists:keysearch(Name, 1, List)
In the second form of function calls,
If
handle(Msg, State)
spawn(m, init, [])
Examples where ExprF is a fun:
Fun1 = fun(X) -> X+1 end
Fun1(3)
=> 4
fun lists:append/2([1,2], [3,4])
=> [1,2,3,4]
Note that when calling a local function, there is a difference
between using the implicitly or fully qualified function name, as
the latter always refers to the latest version of the module. See
See also the chapter about
If a local function has the same name as an auto-imported BIF,
the semantics is that implicitly qualified function calls are
directed to the locally defined function, not to the BIF. To avoid
confusion, there is a compiler directive available,
Before OTP R14A (ERTS version 5.8), an implicitly qualified function call to a function having the same name as an auto-imported BIF always resulted in the BIF being called. In newer versions of the compiler the local function is instead called. The change is there to avoid that future additions to the set of auto-imported BIFs does not silently change the behavior of old code.
However, to avoid that old (pre R14) code changed its behavior when compiled with OTP version R14A or later, the following restriction applies: If you override the name of a BIF that was auto-imported in OTP versions prior to R14A (ERTS version 5.8) and have an implicitly qualified call to that function in your code, you either need to explicitly remove the auto-import using a compiler directive, or replace the call with a fully qualified function call, otherwise you will get a compilation error. See example below:
-export([length/1,f/1]).
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
length([]) ->
0;
length([H|T]) ->
1 + length(T). %% Calls the local function length/1
f(X) when erlang:length(X) > 3 -> %% Calls erlang:length/1,
%% which is allowed in guards
long.
The same logic applies to explicitly imported functions from other modules as to locally defined functions. To both import a function from another module and have the function declared in the module at the same time is not allowed.
-export([f/1]).
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
-import(mod,[length/1]).
f(X) when erlang:length(X) > 33 -> %% Calls erlang:length/1,
%% which is allowed in guards
erlang:length(X); %% Explicit call to erlang:length in body
f(X) ->
length(X). %% mod:length/1 is called
For auto-imported BIFs added to Erlang in release R14A and thereafter,
overriding the name with a local function or explicit import is always
allowed. However, if the
if GuardSeq1 -> Body1; ...; GuardSeqN -> BodyN end
The branches of an
The return value of
If no guard sequence is true, an
Example:
is_greater_than(X, Y) -> if X>Y -> true; true -> % works as an 'else' branch false end
case Expr of Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN end
The expression
The return value of
If there is no matching pattern with a true guard sequence,
a
Example:
is_valid_signal(Signal) -> case Signal of {signal, _What, _From, _To} -> true; {signal, _What, _To} -> true; _Else -> false end.
Expr1 ! Expr2
Sends the value of
receive Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN end
Receives messages sent to the process using the send operator
(!). The patterns
The return value of
Example:
wait_for_onhook() -> receive onhook -> disconnect(), idle(); {connect, B} -> B ! {busy, self()}, wait_for_onhook() end.
It is possible to augment the
receive Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN after ExprT -> BodyT end
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 ExprT -> BodyT end
This construction will not consume any messages, only suspend
execution in the process for
Example:
timer() -> spawn(m, timer, [self()]). timer(Pid) -> receive after 5000 -> Pid ! timeout end.
There are two special cases for the timeout value
Expr1 op Expr2
The arguments may be of different data types. The following order is defined:
number < atom < reference < fun < port < pid < tuple < list < bit string
Lists are compared element by element. Tuples are ordered by size, two tuples with the same size are compared element by element.
When comparing an integer to a float, the term with the lesser precision will be converted into the other term's type, unless the operator is one of =:= or =/=. A float is more precise than an integer until all significant figures of the float are to the left of the decimal point. This happens when the float is larger/smaller than +/-9007199254740992.0. The conversion strategy is changed depending on the size of the float because otherwise comparison of large floats and integers would lose their transitivity.
Returns the Boolean value of the expression,
Examples:
1> 1==1.0. true 2> 1=:=1.0. false 3> 1 > a. false
op Expr Expr1 op Expr2
Examples:
1> +1. 1 2> -1. -1 3> 1+1. 2 4> 4/2. 2.0 5> 5 div 2. 2 6> 5 rem 2. 1 7> 2#10 band 2#01. 0 8> 2#10 bor 2#01. 3 9> a + 10. ** exception error: an error occurred when evaluating an arithmetic expression in operator +/2 called as a + 10 10> 1 bsl (1 bsl 64). ** exception error: a system limit has been reached in operator bsl/2 called as 1 bsl 18446744073709551616
op Expr Expr1 op Expr2
Examples:
1> not true. false 2> true and false. false 3> true xor false. true 4> true or garbage. ** exception error: bad argument in operator or/2 called as true or garbage
Expr1 orelse Expr2 Expr1 andalso Expr2
Expressions where
Example 1:
case A >= -1.0 andalso math:sqrt(A+1) > B of
This will work even if
Example 2:
OnlyOne = is_atom(L) orelse (is_list(L) andalso length(L) == 1),
From R13A,
all(Pred, [Hd|Tail]) -> Pred(Hd) andalso all(Pred, Tail); all(_, []) -> true.
Expr1 ++ Expr2 Expr1 -- Expr2
The list concatenation operator
The list subtraction operator
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]
The complexity of
Constructing a new map is done by letting an expression
#{ K => V }
New maps may include multiple associations at construction by listing every association:
#{ K1 => V1, .., Kn => Vn }
An empty map is constructed by not associating any terms with each other:
#{}
All keys and values in the map are terms. Any expression is first evaluated and then the resulting terms are used as key and value respectively.
Keys and values are separated by the
Examples:
M0 = #{}, % empty map
M1 = #{a => <<"hello">>}, % single association with literals
M2 = #{1 => 2, b => b}, % multiple associations with literals
M3 = #{k => {A,B}}, % single association with variables
M4 = #{{"w", 1} => f()}. % compound key associated with an evaluated expression
where,
If two matching keys are declared, the latter key will take precedence.
Example:
1> #{1 => a, 1 => b}. #{1 => b } 2> #{1.0 => a, 1 => b}. #{1 => b, 1.0 => a}
The order in which the expressions constructing the keys and their associated values are evaluated is not defined. The syntactic order of the key-value pairs in the construction is of no relevance, except in the above mentioned case of two matching keys.
Updating a map has similar syntax as constructing it.
An expression defining the map to be updated is put in front of the expression defining the keys to be updated and their respective values.
M#{ K => V }
where
If key
If
To only update an existing value, the following syntax is used,
M#{ K := V }
where
If key
If
Examples:
M0 = #{},
M1 = M0#{a => 0},
M2 = M1#{a => 1, b => 2},
M3 = M2#{"function" => fun() -> f() end},
M4 = M3#{a := 2, b := 3}. % 'a' and 'b' was added in `M1` and `M2`.
where
More Examples:
1> M = #{1 => a}. #{1 => a } 2> M#{1.0 => b}. #{1 => a, 1.0 => b}. 3> M#{1 := b}. #{1 => b} 4> M#{1.0 := b}. ** exception error: bad argument
As in construction, the order in which the key and value expressions are evaluated is not defined. The syntactic order of the key-value pairs in the update is of no relevance, except in the case where two keys match, in which case the latter value is used.
Matching of key-value associations from maps is done in the following way:
#{ K := V } = M
where
If the variable
Example:
1> M = #{"tuple" => {1,2}}.
#{"tuple" => {1,2}}
2> #{"tuple" := {1,B}} = M.
#{"tuple" => {1,2}}
3> B.
2.
This will bind variable
Similarly, multiple values from the map may be matched:
#{ K1 := V1, .., Kn := Vn } = M
where keys
If the matching conditions are not met, the match will fail, either with
Matching in maps only allows for
Duplicate keys are allowed in matching and will match each pattern associated to the keys.
#{ K := V1, K := V2 } = M
Matching an expression against an empty map literal will match its type but no variables will be bound:
#{} = Expr
This expression will match if the expression
Matching of literals as keys are allowed in function heads.
%% only start if not_started
handle_call(start, From, #{ state := not_started } = S) ->
...
{reply, ok, S#{ state := start }};
%% only change if started
handle_call(change, From, #{ state := start } = S) ->
...
{reply, ok, S#{ state := changed }};
Maps are allowed in guards as long as all sub-expressions are valid guard expressions.
Two guard BIFs handles maps:
>
<>]]>
Each element
Ei = Value | Value:Size | Value/TypeSpecifierList | Value:Size/TypeSpecifierList
Used in a bit string construction,
Used in a bit string matching,
Note that, for example, using a string literal as in
Used in a bit string construction,
Used in a bit string matching,
The value of
For the
The value of
When constructing binaries, if the size
The types
When constructing a segment of a
When constructing, a literal string may be given followed
by one of the UTF types, for example:
A successful match of a segment of a
A segment of type
A segment of type
A segment of type
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>> 11> <<G,H/bitstring>> = <<1,17,42:12>>. <<1,17,1,10:4>> 12> H. <<17,1,10:4>> 13> <<1024/utf8>>. <<208,128>>
Note that bit string patterns cannot be nested.
Note also that "
More examples can be found in Programming Examples.
fun [Name](Pattern11,...,Pattern1N) [when GuardSeq1] -> Body1; ...; [Name](PatternK1,...,PatternKN) [when GuardSeqK] -> BodyK end
A fun expression begins with the keyword
Variables in a fun head shadow the function name and both 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 5> Fun3 = fun Fact(1) -> 1; Fact(X) when X > 1 -> X * Fact(X - 1) end. #Fun<erl_eval.6.39074546> 6> Fun3(4). 24
The following fun expressions are also allowed:
fun Name/Arity fun Module:Name/Arity
In
fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end
In
More examples can be found in Programming Examples.
catch Expr
Returns the value of
Examples:
1> catch 1+2. 3 2> catch 1+a. {'EXIT',{badarith,[...]}}
Note that
3> A = catch 1+2. ** 1: syntax error before: 'catch' ** 4> A = (catch 1+2). 3
The BIF
5> catch throw(hello). hello
If
try Exprs
catch
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
ExceptionBody1;
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
ExceptionBodyN
end
This is an enhancement of
Note that although the keyword
Returns the value of
If an exception occurs during evaluation of
If an exception occurs during evaluation of
The
try Exprs 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
An exception occurring during the evaluation of
The
try Exprs of
Pattern1 [when GuardSeq1] ->
Body1;
...;
PatternN [when GuardSeqN] ->
BodyN
catch
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
ExceptionBody1;
...;
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
ExceptionBodyN
after
AfterBody
end
Even if an exception occurs during evaluation of
If an exception occurs during evaluation of
The
try Exprs of
Pattern when GuardSeq ->
Body
after
AfterBody
end
try Exprs
catch
ExpressionPattern ->
ExpressionBody
after
AfterBody
end
try Exprs after AfterBody end
Example of using
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 Expr
catch
throw:Term -> Term;
exit:Reason -> {'EXIT',Reason}
error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}}
end
(Expr)
Parenthesized expressions are useful to override
1> 1 + 2 * 3. 7 2> (1 + 2) * 3. 9
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
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
List comprehensions are written with the following syntax:
[Expr || Qualifier1,...,QualifierN]
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
Example:
1> [X*2 || X <- [1,2,3]]. [2,4,6]
More examples can be found in Programming Examples.
Bit string comprehensions are analogous to List Comprehensions. They are used to generate bit strings efficiently and succinctly.
Bit string comprehensions are written with the following syntax:
<< BitString || Qualifier1,...,QualifierN >>
The variables in the generator patterns shadow variables in the function clause surrounding the bit string comprehensions.
A bit string comprehension returns a bit string, which is
created by concatenating the results of evaluating
Example:
1> << << (X*2) >> || <<X>> <= << 1,2,3 >> >>. <<2,4,6>>
More examples can be found in Programming Examples.
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. (The remaining guards, if any, will not be
evaluated.)
A guard is a sequence of guard expressions, separated
by comma (,). The guard is true if all guard expressions
evaluate to
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:
Note that most type test BIFs have older equivalents, without
the
If an arithmetic expression, a boolean expression, a short-circuit expression, or a call to a guard BIF fails (because of invalid arguments), the entire guard fails. If the guard was part of a guard sequence, the next guard in the sequence (that is, the guard following the next semicolon) will be evaluated.
Operator precedence in falling priority:
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 arithmetic 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