1
<?xml version="1.0" encoding="latin1" ?>
2
<!DOCTYPE chapter SYSTEM "chapter.dtd">
7
<year>2003</year><year>2011</year>
8
<holder>Ericsson AB. All Rights Reserved.</holder>
11
The contents of this file are subject to the Erlang Public License,
12
Version 1.1, (the "License"); you may not use this file except in
13
compliance with the License. You should have received a copy of the
14
Erlang Public License along with this software. If not, it can be
15
retrieved online at http://www.erlang.org/.
17
Software distributed under the License is distributed on an "AS IS"
18
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
19
the License for the specific language governing rights and limitations
24
<title>Expressions</title>
29
<file>expressions.xml</file>
31
<p>In this chapter, all valid Erlang expressions are listed.
32
When writing Erlang programs, it is also allowed to use macro-
33
and record expressions. However, these expressions are expanded
34
during compilation and are in that sense not true Erlang
35
expressions. Macro- and record expressions are covered in
36
separate chapters: <seealso marker="macros">Macros</seealso> and
37
<seealso marker="records">Records</seealso>.</p>
40
<title>Expression Evaluation</title>
41
<p>All subexpressions are evaluated before an expression itself is
42
evaluated, unless explicitly stated otherwise. For example,
43
consider the expression:</p>
46
<p><c>Expr1</c> and <c>Expr2</c>, which are also expressions, are
47
evaluated first - in any order - before the addition is
49
<p>Many of the operators can only be applied to arguments of a
50
certain type. For example, arithmetic operators can only be
51
applied to numbers. An argument of the wrong type will cause
52
a <c>badarg</c> run-time error.</p>
56
<marker id="term"></marker>
58
<p>The simplest form of expression is a term, that is an integer,
59
float, atom, string, list or tuple.
60
The return value is the term itself.</p>
64
<title>Variables</title>
65
<p>A variable is an expression. If a variable is bound to a value,
66
the return value is this value. Unbound variables are only
67
allowed in patterns.</p>
68
<p>Variables start with an uppercase letter or underscore (_)
69
and may contain alphanumeric characters, underscore and @.
78
<p>Variables are bound to values using
79
<seealso marker="patterns">pattern matching</seealso>. Erlang
80
uses <em>single assignment</em>, a variable can only be bound
82
<p>The <em>anonymous variable</em> is denoted by underscore (_) and
83
can be used when a variable is required but its value can be
87
<p>Variables starting with underscore (_), for example
88
<c>_Height</c>, are normal variables, not anonymous. They are
89
however ignored by the compiler in the sense that they will not
90
generate any warnings for unused variables. Example: The following
95
<p>can be rewritten to be more readable:</p>
99
<p>This will however cause a warning for an unused variable
100
<c>Elem</c>, if the code is compiled with the flag
101
<c>warn_unused_vars</c> set. Instead, the code can be rewritten
106
<p>Note that since variables starting with an underscore are
107
not anonymous, this will match:</p>
110
<p>But this will fail:</p>
112
{_N,_N} = {1,2}</pre>
113
<p>The scope for a variable is its function clause.
114
Variables bound in a branch of an <c>if</c>, <c>case</c>,
115
or <c>receive</c> expression must be bound in all branches
116
to have a value outside the expression, otherwise they
117
will be regarded as 'unsafe' outside the expression.</p>
118
<p>For the <c>try</c> expression introduced in
119
Erlang 5.4/OTP-R10B, variable scoping is limited so that
120
variables bound in the expression are always 'unsafe' outside
121
the expression. This will be improved.</p>
125
<marker id="pattern"></marker>
126
<title>Patterns</title>
127
<p>A pattern has the same structure as a term but may contain
128
unbound variables. Example:</p>
133
<p>Patterns are allowed in clause heads, <c>case</c> and
134
<c>receive</c> expressions, and match expressions.</p>
137
<title>Match Operator = in Patterns</title>
138
<p>If <c>Pattern1</c> and <c>Pattern2</c> are valid patterns,
139
then the following is also a valid pattern:</p>
141
Pattern1 = Pattern2</pre>
142
<p>When matched against a term, both <c>Pattern1</c> and
143
<c>Pattern2</c> will be matched against the term. The idea
144
behind this feature is to avoid reconstruction of terms.
147
f({connect,From,To,Number,Options}, To) ->
148
Signal = {connect,From,To,Number,Options},
152
<p>can instead be written as</p>
154
f({connect,_,To,_,_} = Signal, To) ->
161
<title>String Prefix in Patterns</title>
162
<p>When matching strings, the following is a valid pattern:</p>
164
f("prefix" ++ Str) -> ...</pre>
165
<p>This is syntactic sugar for the equivalent, but harder to
168
f([$p,$r,$e,$f,$i,$x | Str]) -> ...</pre>
172
<title>Expressions in Patterns</title>
173
<p>An arithmetic expression can be used within a pattern, if
174
it uses only numeric or bitwise operators, and if its value
175
can be evaluated to a constant at compile-time. Example:</p>
177
case {Value, Result} of
178
{?THRESHOLD+1, ok} -> ...</pre>
179
<p>This feature was added in Erlang 5.0/OTP R7.</p>
187
<p>Matches <c>Expr1</c>, a pattern, against <c>Expr2</c>.
188
If the matching succeeds, any unbound variable in the pattern
189
becomes bound and the value of <c>Expr2</c> is returned.</p>
190
<p>If the matching fails, a <c>badmatch</c> run-time error will
194
1> <input>{A, B} = {answer, 42}.</input>
198
3> <input>{C, D} = [1, 2].</input>
199
** exception error: no match of right hand side value [1,2]</pre>
203
<marker id="calls"></marker>
204
<title>Function Calls</title>
206
ExprF(Expr1,...,ExprN)
207
ExprM:ExprF(Expr1,...,ExprN)</pre>
208
<p>In the first form of function calls,
209
<c>ExprM:ExprF(Expr1,...,ExprN)</c>, each of <c>ExprM</c> and
210
<c>ExprF</c> must be an atom or an expression that evaluates to
211
an atom. The function is said to be called by using the
212
<em>fully qualified function name</em>. This is often referred
213
to as a <em>remote</em> or <em>external function call</em>.
216
lists:keysearch(Name, 1, List)</code>
217
<p>In the second form of function calls,
218
<c>ExprF(Expr1,...,ExprN)</c>, <c>ExprF</c> must be an atom or
219
evaluate to a fun.</p>
221
<p>If <c>ExprF</c> is an atom the function is said to be called by
222
using the <em>implicitly qualified function name</em>. If the
223
function <c>ExprF</c> is locally defined, it is called.
224
Alternatively if <c>ExprF</c> is explicitly imported from module
225
<c>M</c>, <c>M:ExprF(Expr1,...,ExprN)</c> is called. If
226
<c>ExprF</c> is neither declared locally nor explicitly
227
imported, <c>ExprF</c> must be the name of an automatically
228
imported BIF. Examples:</p>
232
spawn(m, init, [])</code>
233
<p>Examples where ExprF is a fun:</p>
235
Fun1 = fun(X) -> X+1 end
239
Fun2 = {lists,append}
243
fun lists:append/2([1,2], [3,4])
246
<p>Note that when calling a local function, there is a difference
247
between using the implicitly or fully qualified function name, as
248
the latter always refers to the latest version of the module. See
249
<seealso marker="code_loading">Compilation and Code Loading</seealso>.</p>
251
<p>See also the chapter about
252
<seealso marker="functions#eval">Function Evaluation</seealso>.</p>
255
<title>Local Function Names Clashing With Auto-imported BIFs</title>
256
<p>If a local function has the same name as an auto-imported BIF,
257
the semantics is that implicitly qualified function calls are
258
directed to the locally defined function, not to the BIF. To avoid
259
confusion, there is a compiler directive available,
260
<c>-compile({no_auto_import,[F/A]})</c>, that makes a BIF not
261
being auto-imported. In certain situations, such a compile-directive
264
<warning><p>Before OTP R14A (ERTS version 5.8), an implicitly
265
qualified function call to a function having the same name as an
266
auto-imported BIF always resulted in the BIF being called. In
267
newer versions of the compiler the local function is instead
268
called. The change is there to avoid that future additions to the
269
set of auto-imported BIFs does not silently change the behavior
272
<p>However, to avoid that old (pre R14) code changed its
273
behavior when compiled with OTP version R14A or later, the
274
following restriction applies: If you override the name of a BIF
275
that was auto-imported in OTP versions prior to R14A (ERTS version
276
5.8) and have an implicitly qualified call to that function in
277
your code, you either need to explicitly remove the auto-import
278
using a compiler directive, or replace the call with a fully
279
qualified function call, otherwise you will get a compilation
280
error. See example below:</p> </warning>
283
-export([length/1,f/1]).
285
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
290
1 + length(T). %% Calls the local funtion length/1
292
f(X) when erlang:length(X) > 3 -> %% Calls erlang:length/1,
293
%% which is allowed in guards
296
<p>The same logic applies to explicitly imported functions from
297
other modules as to locally defined functions. To both import a
298
function from another module and have the function declared in the
299
module at the same time is not allowed.</p>
304
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
306
-import(mod,[length/1]).
308
f(X) when erlang:length(X) > 33 -> %% Calls erlang:lenght/1,
309
%% which is allowed in guards
311
erlang:length(X); %% Explicit call to erlang:length in body
314
length(X). %% mod:length/1 is called</code>
317
<p>For auto-imported BIFs added to Erlang in release R14A and thereafter,
318
overriding the name with a local function or explicit import is always
319
allowed. However, if the <c>-compile({no_auto_import,[F/A])</c>
320
directive is not used, the compiler will issue a warning whenever
321
the function is called in the module using the implicitly qualified
336
<p>The branches of an <c>if</c>-expression are scanned sequentially
337
until a guard sequence <c>GuardSeq</c> which evaluates to true is
338
found. Then the corresponding <c>Body</c> (sequence of expressions
339
separated by ',') is evaluated.</p>
340
<p>The return value of <c>Body</c> is the return value of
341
the <c>if</c> expression.</p>
342
<p>If no guard sequence is true, an <c>if_clause</c> run-time error
343
will occur. If necessary, the guard expression <c>true</c> can be
344
used in the last branch, as that guard sequence is always true.</p>
347
is_greater_than(X, Y) ->
351
true -> % works as an 'else' branch
357
<marker id="case"></marker>
361
Pattern1 [when GuardSeq1] ->
364
PatternN [when GuardSeqN] ->
367
<p>The expression <c>Expr</c> is evaluated and the patterns
368
<c>Pattern</c> are sequentially matched against the result. If a
369
match succeeds and the optional guard sequence <c>GuardSeq</c> is
370
true, the corresponding <c>Body</c> is evaluated.</p>
371
<p>The return value of <c>Body</c> is the return value of
372
the <c>case</c> expression.</p>
373
<p>If there is no matching pattern with a true guard sequence,
374
a <c>case_clause</c> run-time error will occur.</p>
377
is_valid_signal(Signal) ->
379
{signal, _What, _From, _To} ->
381
{signal, _What, _To} ->
389
<marker id="send"></marker>
393
<p>Sends the value of <c>Expr2</c> as a message to the process
394
specified by <c>Expr1</c>. The value of <c>Expr2</c> is also
395
the return value of the expression.</p>
396
<p><c>Expr1</c> must evaluate to a pid, a registered name (atom) or
397
a tuple <c>{Name,Node}</c>, where <c>Name</c> is an atom and
398
<c>Node</c> a node name, also an atom.</p>
399
<list type="bulleted">
400
<item>If <c>Expr1</c> evaluates to a name, but this name is not
401
registered, a <c>badarg</c> run-time error will occur.</item>
402
<item>Sending a message to a pid never fails, even if the pid
403
identifies a non-existing process.</item>
404
<item>Distributed message sending, that is if <c>Expr1</c>
405
evaluates to a tuple <c>{Name,Node}</c> (or a pid located at
406
another node), also never fails.</item>
411
<marker id="receive"></marker>
412
<title>Receive</title>
415
Pattern1 [when GuardSeq1] ->
418
PatternN [when GuardSeqN] ->
421
<p>Receives messages sent to the process using the send operator
422
(!). The patterns <c>Pattern</c> are sequentially matched
423
against the first message in time order in the mailbox, then
424
the second, and so on. If a match succeeds and the optional
425
guard sequence <c>GuardSeq</c> is true, the corresponding
426
<c>Body</c> is evaluated. The matching message is consumed, that
427
is removed from the mailbox, while any other messages in
428
the mailbox remain unchanged.</p>
429
<p>The return value of <c>Body</c> is the return value of
430
the <c>receive</c> expression.</p>
431
<p><c>receive</c> never fails. Execution is suspended, possibly
432
indefinitely, until a message arrives that does match one of
433
the patterns and with a true guard sequence. </p>
445
<p>It is possible to augment the <c>receive</c> expression with a
449
Pattern1 [when GuardSeq1] ->
452
PatternN [when GuardSeqN] ->
458
<p><c>ExprT</c> should evaluate to an integer. The highest allowed
459
value is 16#ffffffff, that is, the value must fit in 32 bits.
460
<c>receive..after</c> works exactly as <c>receive</c>, except
461
that if no matching message has arrived within <c>ExprT</c>
462
milliseconds, then <c>BodyT</c> is evaluated instead and its
463
return value becomes the return value of the <c>receive..after</c>
480
<p>It is legal to use a <c>receive..after</c> expression with no
488
<p>This construction will not consume any messages, only suspend
489
execution in the process for <c>ExprT</c> milliseconds and can be
490
used to implement simple timers.</p>
494
spawn(m, timer, [self()]).
502
<p>There are two special cases for the timeout value <c>ExprT</c>:</p>
504
<tag><c>infinity</c></tag>
505
<item>The process should wait indefinitely for a matching message
506
-- this is the same as not using a timeout. Can be
507
useful for timeout values that are calculated at run-time.</item>
509
<item>If there is no matching message in the mailbox, the timeout
510
will occur immediately.</item>
515
<title>Term Comparisons</title>
517
Expr1 <input>op</input> Expr2</pre>
520
<cell align="left" valign="middle"><em>op</em></cell>
521
<cell align="left" valign="middle"><em>Description</em></cell>
524
<cell align="left" valign="middle">==</cell>
525
<cell align="left" valign="middle">equal to</cell>
528
<cell align="left" valign="middle">/=</cell>
529
<cell align="left" valign="middle">not equal to</cell>
532
<cell align="left" valign="middle">=<</cell>
533
<cell align="left" valign="middle">less than or equal to</cell>
536
<cell align="left" valign="middle"><</cell>
537
<cell align="left" valign="middle">less than</cell>
540
<cell align="left" valign="middle">>=</cell>
541
<cell align="left" valign="middle">greater than or equal to</cell>
544
<cell align="left" valign="middle">></cell>
545
<cell align="left" valign="middle">greater than</cell>
548
<cell align="left" valign="middle">=:=</cell>
549
<cell align="left" valign="middle">exactly equal to</cell>
552
<cell align="left" valign="middle">=/=</cell>
553
<cell align="left" valign="middle">exactly not equal to</cell>
555
<tcaption>Term Comparison Operators.</tcaption>
557
<p>The arguments may be of different data types. The following
558
order is defined:</p>
560
number < atom < reference < fun < port < pid < tuple < list < bit string</pre>
561
<p>Lists are compared element by element. Tuples are ordered by
562
size, two tuples with the same size are compared element by
564
<p>If one of the compared terms is an integer and the other a
565
float, the integer is first converted into a float, unless the
566
operator is one of =:= and =/=. If the integer is too big to fit
567
in a float no conversion is done, but the order is determined by
568
inspecting the sign of the numbers.</p>
569
<p>Returns the Boolean value of the expression, <c>true</c> or
573
1> <input>1==1.0.</input>
575
2> <input>1=:=1.0.</input>
577
3> <input>1 > a.</input>
582
<title>Arithmetic Expressions</title>
584
<input>op</input> Expr
585
Expr1 <input>op</input> Expr2</pre>
588
<cell align="left" valign="middle"><em>op</em></cell>
589
<cell align="left" valign="middle"><em>Description</em></cell>
590
<cell align="left" valign="middle"><em>Argument type</em></cell>
593
<cell align="left" valign="middle">+</cell>
594
<cell align="left" valign="middle">unary +</cell>
595
<cell align="left" valign="middle">number</cell>
598
<cell align="left" valign="middle">-</cell>
599
<cell align="left" valign="middle">unary -</cell>
600
<cell align="left" valign="middle">number</cell>
603
<cell align="left" valign="middle">+</cell>
604
<cell align="left" valign="middle"> </cell>
605
<cell align="left" valign="middle">number</cell>
608
<cell align="left" valign="middle">-</cell>
609
<cell align="left" valign="middle"> </cell>
610
<cell align="left" valign="middle">number</cell>
613
<cell align="left" valign="middle">*</cell>
614
<cell align="left" valign="middle"> </cell>
615
<cell align="left" valign="middle">number</cell>
618
<cell align="left" valign="middle">/</cell>
619
<cell align="left" valign="middle">floating point division</cell>
620
<cell align="left" valign="middle">number</cell>
623
<cell align="left" valign="middle">bnot</cell>
624
<cell align="left" valign="middle">unary bitwise not</cell>
625
<cell align="left" valign="middle">integer</cell>
628
<cell align="left" valign="middle">div</cell>
629
<cell align="left" valign="middle">integer division</cell>
630
<cell align="left" valign="middle">integer</cell>
633
<cell align="left" valign="middle">rem</cell>
634
<cell align="left" valign="middle">integer remainder of X/Y</cell>
635
<cell align="left" valign="middle">integer</cell>
638
<cell align="left" valign="middle">band</cell>
639
<cell align="left" valign="middle">bitwise and</cell>
640
<cell align="left" valign="middle">integer</cell>
643
<cell align="left" valign="middle">bor</cell>
644
<cell align="left" valign="middle">bitwise or</cell>
645
<cell align="left" valign="middle">integer</cell>
648
<cell align="left" valign="middle">bxor</cell>
649
<cell align="left" valign="middle">arithmetic bitwise xor</cell>
650
<cell align="left" valign="middle">integer</cell>
653
<cell align="left" valign="middle">bsl</cell>
654
<cell align="left" valign="middle">arithmetic bitshift left</cell>
655
<cell align="left" valign="middle">integer</cell>
658
<cell align="left" valign="middle">bsr</cell>
659
<cell align="left" valign="middle">bitshift right</cell>
660
<cell align="left" valign="middle">integer</cell>
662
<tcaption>Arithmetic Operators.</tcaption>
667
1> <input>+1.</input>
669
2> <input>-1.</input>
671
3> <input>1+1.</input>
673
4> <input>4/2.</input>
675
5> <input>5 div 2.</input>
677
6> <input>5 rem 2.</input>
679
7> <input>2#10 band 2#01.</input>
681
8> <input>2#10 bor 2#01.</input>
683
9> <input>a + 10.</input>
684
** exception error: bad argument in an arithmetic expression
687
10> <input>1 bsl (1 bsl 64).</input>
688
** exception error: a system limit has been reached
690
called as 1 bsl 18446744073709551616</pre>
694
<title>Boolean Expressions</title>
696
<input>op</input> Expr
697
Expr1 <input>op</input> Expr2</pre>
700
<cell align="left" valign="middle"><em>op</em></cell>
701
<cell align="left" valign="middle"><em>Description</em></cell>
704
<cell align="left" valign="middle">not</cell>
705
<cell align="left" valign="middle">unary logical not</cell>
708
<cell align="left" valign="middle">and</cell>
709
<cell align="left" valign="middle">logical and</cell>
712
<cell align="left" valign="middle">or</cell>
713
<cell align="left" valign="middle">logical or</cell>
716
<cell align="left" valign="middle">xor</cell>
717
<cell align="left" valign="middle">logical xor</cell>
719
<tcaption>Logical Operators.</tcaption>
723
1> <input>not true.</input>
725
2> <input>true and false.</input>
727
3> <input>true xor false.</input>
729
4> <input>true or garbage.</input>
730
** exception error: bad argument
732
called as true or garbage</pre>
736
<title>Short-Circuit Expressions</title>
739
Expr1 andalso Expr2</pre>
740
<p>Expressions where <c>Expr2</c> is evaluated only if
741
necessary. That is, <c>Expr2</c> is evaluated only if <c>Expr1</c>
742
evaluates to <c>false</c> in an <c>orelse</c> expression, or only
743
if <c>Expr1</c> evaluates to <c>true</c> in an <c>andalso</c>
744
expression. Returns either the value of <c>Expr1</c> (that is,
745
<c>true</c> or <c>false</c>) or the value of <c>Expr2</c>
746
(if <c>Expr2</c> was evaluated).</p>
750
case A >= -1.0 andalso math:sqrt(A+1) > B of</pre>
751
<p>This will work even if <c>A</c> is less than <c>-1.0</c>,
752
since in that case, <c>math:sqrt/1</c> is never evaluated.</p>
755
OnlyOne = is_atom(L) orelse
756
(is_list(L) andalso length(L) == 1),</pre>
758
<p>From R13A, <c>Expr2</c> is no longer required to evaluate to a
759
boolean value. As a consequence, <c>andalso</c> and <c>orelse</c>
760
are now tail-recursive. For instance, the following function is
761
tail-recursive in R13A and later:</p>
764
all(Pred, [Hd|Tail]) ->
765
Pred(Hd) andalso all(Pred, Tail);
771
<title>List Operations</title>
775
<p>The list concatenation operator <c>++</c> appends its second
776
argument to its first and returns the resulting list.</p>
777
<p>The list subtraction operator <c>--</c> produces a list which
778
is a copy of the first argument, subjected to the following
779
procedure: for each element in the second argument, the first
780
occurrence of this element (if any) is removed.</p>
783
1> <input>[1,2,3]++[4,5].</input>
785
2> <input>[1,2,3,2,1,2]--[2,1,2].</input>
788
<warning><p>The complexity of <c>A -- B</c> is
789
proportional to <c>length(A)*length(B)</c>, meaning that it
790
will be very slow if both <c>A</c> and <c>B</c> are
791
long lists.</p></warning>
795
<marker id="bit_syntax"></marker>
796
<title>Bit Syntax Expressions</title>
797
<code type="none"><![CDATA[<<>>
798
<<E1,...,En>>]]></code>
799
<p>Each element <c>Ei</c> specifies a <em>segment</em> of
800
the bit string. Each element <c>Ei</c> is a value, followed by an
801
optional <em>size expression</em> and an optional <em>type specifier list</em>.</p>
805
Value/TypeSpecifierList |
806
Value:Size/TypeSpecifierList</pre>
807
<p>Used in a bit string construction, <c>Value</c> is an expression
808
which should evaluate to an integer, float or bit string. If the
809
expression is something else than a single literal or variable, it
810
should be enclosed in parenthesis.</p>
812
<p>Used in a bit string matching, <c>Value</c> must be a variable,
813
or an integer, float or string.</p>
815
<p>Note that, for example, using a string literal as in
816
<c><![CDATA[<<"abc">>]]></c> is syntactic sugar for
817
<c><![CDATA[<<$a,$b,$c>>]]></c>.</p>
819
<p>Used in a bit string construction, <c>Size</c> is an expression
820
which should evaluate to an integer.</p>
822
<p>Used in a bit string matching, <c>Size</c> must be an integer or a
823
variable bound to an integer.</p>
825
<p>The value of <c>Size</c> specifies the size of the segment in
826
units (see below). The default value depends on the type (see
827
below). For <c>integer</c> it is 8, for
828
<c>float</c> it is 64, for <c>binary</c> and <c>bitstring</c> it is
829
the whole binary or bit string. In matching, this default value is only
830
valid for the very last element. All other bit string or binary
831
elements in the matching must have a size specification.</p>
833
<p>For the <c>utf8</c>, <c>utf16</c>, and <c>utf32</c> types,
834
<c>Size</c> must not be given. The size of the segment is implicitly
835
determined by the type and value itself.</p>
837
<p><c>TypeSpecifierList</c> is a list of type specifiers, in any
838
order, separated by hyphens (-). Default values are used for any
839
omitted type specifiers.</p>
841
<tag><c>Type</c>= <c>integer</c> | <c>float</c> | <c>binary</c> |
842
<c>bytes</c> | <c>bitstring</c> | <c>bits</c> |
843
<c>utf8</c> | <c>utf16</c> | <c>utf32</c> </tag>
844
<item>The default is <c>integer</c>. <c>bytes</c> is a shorthand for
845
<c>binary</c> and <c>bits</c> is a shorthand for <c>bitstring</c>.
846
See below for more information about the <c>utf</c> types.
849
<tag><c>Signedness</c>= <c>signed</c> | <c>unsigned</c></tag>
850
<item>Only matters for matching and when the type is <c>integer</c>.
851
The default is <c>unsigned</c>.</item>
853
<tag><c>Endianness</c>= <c>big</c> | <c>little</c> | <c>native</c></tag>
854
<item>Native-endian means that the endianness will be resolved at load
855
time to be either big-endian or little-endian, depending on
856
what is native for the CPU that the Erlang machine is run on.
857
Endianness only matters when the Type is either <c>integer</c>,
858
<c>utf16</c>, <c>utf32</c>, or <c>float</c>. The default is <c>big</c>.
861
<tag><c>Unit</c>= <c>unit:IntegerLiteral</c></tag>
862
<item>The allowed range is 1..256. Defaults to 1 for <c>integer</c>,
863
<c>float</c> and <c>bitstring</c>, and to 8 for <c>binary</c>.
864
No unit specifier must be given for the types
865
<c>utf8</c>, <c>utf16</c>, and <c>utf32</c>.
868
<p>The value of <c>Size</c> multiplied with the unit gives
869
the number of bits. A segment of type <c>binary</c> must have
870
a size that is evenly divisible by 8.</p>
872
<note><p>When constructing binaries, if the size <c>N</c> of an integer
873
segment is too small to contain the given integer, the most significant
874
bits of the integer will be silently discarded and only the <c>N</c> least
875
significant bits will be put into the binary.</p></note>
877
<p>The types <c>utf8</c>, <c>utf16</c>, and <c>utf32</c> specifies
878
encoding/decoding of the <em>Unicode Transformation Format</em>s UTF-8, UTF-16,
879
and UTF-32, respectively.</p>
881
<p>When constructing a segment of a <c>utf</c> type, <c>Value</c>
882
must be an integer in one of the ranges 0..16#D7FF,
883
16#E000..16#FFFD, or 16#10000..16#10FFFF
884
(i.e. a valid Unicode code point). Construction
885
will fail with a <c>badarg</c> exception if <c>Value</c> is
886
outside the allowed ranges. The size of the resulting binary
887
segment depends on the type and/or <c>Value</c>. For <c>utf8</c>,
888
<c>Value</c> will be encoded in 1 through 4 bytes. For
889
<c>utf16</c>, <c>Value</c> will be encoded in 2 or 4
890
bytes. Finally, for <c>utf32</c>, <c>Value</c> will always be
891
encoded in 4 bytes.</p>
893
<p>When constructing, a literal string may be given followed
894
by one of the UTF types, for example: <c><![CDATA[<<"abc"/utf8>>]]></c>
895
which is syntatic sugar for
896
<c><![CDATA[<<$a/utf8,$b/utf8,$c/utf8>>]]></c>.</p>
898
<p>A successful match of a segment of a <c>utf</c> type results
899
in an integer in one of the ranges 0..16#D7FF, 16#E000..16#FFFD,
900
or 16#10000..16#10FFFF
901
(i.e. a valid Unicode code point). The match will fail if returned value
902
would fall outside those ranges.</p>
904
<p>A segment of type <c>utf8</c> will match 1 to 4 bytes in the binary,
905
if the binary at the match position contains a valid UTF-8 sequence.
906
(See RFC-2279 or the Unicode standard.)</p>
908
<p>A segment of type <c>utf16</c> may match 2 or 4 bytes in the binary.
909
The match will fail if the binary at the match position does not contain
910
a legal UTF-16 encoding of a Unicode code point. (See RFC-2781 or
911
the Unicode standard.)</p>
913
<p>A segment of type <c>utf32</c> may match 4 bytes in the binary in the
914
same way as an <c>integer</c> segment matching 32 bits.
915
The match will fail if the resulting integer is outside the legal ranges
920
1> <input>Bin1 = <<1,17,42>>.</input>
921
<<1,17,42>>
922
2> <input>Bin2 = <<"abc">>.</input>
923
<<97,98,99>>
924
3> <input>Bin3 = <<1,17,42:16>>.</input>
925
<<1,17,0,42>>
926
4> <input><<A,B,C:16>> = <<1,17,42:16>>.</input>
927
<<1,17,0,42>>
930
6> <input><<D:16,E,F>> = <<1,17,42:16>>.</input>
931
<<1,17,0,42>>
936
9> <input><<G,H/binary>> = <<1,17,42:16>>.</input>
937
<<1,17,0,42>>
938
10> <input>H.</input>
939
<<17,0,42>>
940
11> <input><<G,H/bitstring>> = <<1,17,42:12>>.</input>
941
<<1,17,1,10:4>>
942
12> <input>H.</input>
943
<<17,1,10:4>>
944
13> <input><<1024/utf8>>.</input>
945
<<208,128>>
947
<p>Note that bit string patterns cannot be nested.</p>
948
<p>Note also that "<c><![CDATA[B=<<1>>]]></c>" is interpreted as
949
"<c><![CDATA[B =<<1>>]]></c>" which is a syntax error. The correct way is
950
to write a space after '=': "<c><![CDATA[B= <<1>>]]></c>.</p>
951
<p>More examples can be found in <em>Programming Examples</em>.</p>
955
<marker id="funs"></marker>
956
<title>Fun Expressions</title>
959
(Pattern11,...,Pattern1N) [when GuardSeq1] ->
962
(PatternK1,...,PatternKN) [when GuardSeqK] ->
965
<p>A fun expression begins with the keyword <c>fun</c> and ends
966
with the keyword <c>end</c>. Between them should be a function
967
declaration, similar to a
968
<seealso marker="functions#syntax">regular function declaration</seealso>, except that no function name is
970
<p>Variables in a fun head shadow variables in the
971
function clause surrounding the fun expression, and
972
variables bound in a fun body are local to the fun body.</p>
973
<p>The return value of the expression is the resulting fun.</p>
976
1> <input>Fun1 = fun (X) -> X+1 end.</input>
977
#Fun<erl_eval.6.39074546>
978
2> <input>Fun1(2).</input>
980
3> <input>Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.</input>
981
#Fun<erl_eval.6.39074546>
982
4> <input>Fun2(7).</input>
984
<p>The following fun expressions are also allowed:</p>
987
fun Module:Name/Arity</pre>
988
<p>In <c>Name/Arity</c>, <c>Name</c> is an atom and <c>Arity</c> is an integer.
989
<c>Name/Arity</c> must specify an existing local function. The expression is
990
syntactic sugar for:</p>
992
fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end</pre>
993
<p>In <c>Module:Name/Arity</c>, <c>Module</c> and <c>Name</c> are atoms
994
and <c>Arity</c> is an integer.
995
A fun defined in this way will refer to the function <c>Name</c>
996
with arity <c>Arity</c> in the <em>latest</em> version of module <c>Module</c>.
998
<p>When applied to a number N of arguments, a tuple
999
<c>{Module,FunctionName}</c> is interpreted as a fun, referring
1000
to the function <c>FunctionName</c> with arity N in the module
1001
<c>Module</c>. The function must be exported.
1002
<em>This usage is deprecated.</em>
1003
See <seealso marker="#calls">Function Calls</seealso> for an example.</p>
1004
<p>More examples can be found in <em>Programming Examples</em>.</p>
1008
<marker id="catch"></marker>
1009
<title>Catch and Throw</title>
1012
<p>Returns the value of <c>Expr</c> unless an exception
1013
occurs during the evaluation. In that case, the exception is
1014
caught. For exceptions of class <c>error</c>,
1015
that is run-time errors: <c>{'EXIT',{Reason,Stack}}</c>
1016
is returned. For exceptions of class <c>exit</c>, that is
1017
the code called <c>exit(Term)</c>: <c>{'EXIT',Term}</c> is returned.
1018
For exceptions of class <c>throw</c>, that is
1019
the code called <c>throw(Term)</c>: <c>Term</c> is returned.</p>
1020
<p><c>Reason</c> depends on the type of error that occurred, and
1021
<c>Stack</c> is the stack of recent function calls, see
1022
<seealso marker="errors#exit_reasons">Errors and Error Handling</seealso>.</p>
1026
1> <input>catch 1+2.</input>
1028
2> <input>catch 1+a.</input>
1029
{'EXIT',{badarith,[...]}}</pre>
1030
<p>Note that <c>catch</c> has low precedence and catch
1031
subexpressions often needs to be enclosed in a block
1032
expression or in parenthesis:</p>
1034
3> <input>A = catch 1+2.</input>
1035
** 1: syntax error before: 'catch' **
1036
4> <input>A = (catch 1+2).</input>
1038
<p>The BIF <c>throw(Any)</c> can be used for non-local return from
1039
a function. It must be evaluated within a <c>catch</c>, which will
1040
return the value <c>Any</c>. Example:</p>
1042
5> <input>catch throw(hello).</input>
1044
<p>If <c>throw/1</c> is not evaluated within a catch, a
1045
<c>nocatch</c> run-time error will occur.</p>
1049
<marker id="try"></marker>
1054
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
1056
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
1059
<p>This is an enhancement of
1060
<seealso marker="#catch">catch</seealso> that appeared in
1061
Erlang 5.4/OTP-R10B. It gives the possibility do distinguish
1062
between different exception classes, and to choose to handle only
1063
the desired ones, passing the others on to an enclosing
1064
<c>try</c> or <c>catch</c> or to default error handling.</p>
1065
<p>Note that although the keyword <c>catch</c> is used in
1066
the <c>try</c> expression, there is not a <c>catch</c> expression
1067
within the <c>try</c> expression.</p>
1068
<p>Returns the value of <c>Exprs</c> (a sequence of expressions
1069
<c>Expr1, ..., ExprN</c>) unless an exception occurs during
1070
the evaluation. In that case the exception is caught and
1071
the patterns <c>ExceptionPattern</c> with the right exception
1072
class <c>Class</c> are sequentially matched against the caught
1073
exception. An omitted <c>Class</c> is shorthand for <c>throw</c>.
1074
If a match succeeds and the optional guard sequence
1075
<c>ExceptionGuardSeq</c> is true, the corresponding
1076
<c>ExceptionBody</c> is evaluated to become the return value.</p>
1077
<p>If an exception occurs during evaluation of <c>Exprs</c> but
1078
there is no matching <c>ExceptionPattern</c> of the right
1079
<c>Class</c> with a true guard sequence, the exception is passed
1080
on as if <c>Exprs</c> had not been enclosed in a <c>try</c>
1082
<p>If an exception occurs during evaluation of <c>ExceptionBody</c>
1083
it is not caught.</p>
1084
<p>The <c>try</c> expression can have an <c>of</c>
1089
Pattern1 [when GuardSeq1] ->
1092
PatternN [when GuardSeqN] ->
1095
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
1098
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
1101
<p>If the evaluation of <c>Exprs</c> succeeds without an exception,
1102
the patterns <c>Pattern</c> are sequentially matched against
1103
the result in the same way as for a
1104
<seealso marker="#case">case</seealso> expression, except that if
1105
the matching fails, a <c>try_clause</c> run-time error will occur.</p>
1106
<p>An exception occurring during the evaluation of <c>Body</c> is
1108
<p>The <c>try</c> expression can also be augmented with an
1109
<c>after</c> section, intended to be used for cleanup with side
1113
Pattern1 [when GuardSeq1] ->
1116
PatternN [when GuardSeqN] ->
1119
[Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
1122
[ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
1127
<p><c>AfterBody</c> is evaluated after either <c>Body</c> or
1128
<c>ExceptionBody</c> no matter which one. The evaluated value of
1129
<c>AfterBody</c> is lost; the return value of the <c>try</c>
1130
expression is the same with an <c>after</c> section as without.</p>
1131
<p>Even if an exception occurs during evaluation of <c>Body</c> or
1132
<c>ExceptionBody</c>, <c>AfterBody</c> is evaluated. In this case
1133
the exception is passed on after <c>AfterBody</c> has been
1134
evaluated, so the exception from the <c>try</c> expression is
1135
the same with an <c>after</c> section as without.</p>
1136
<p>If an exception occurs during evaluation of <c>AfterBody</c>
1137
itself it is not caught, so if <c>AfterBody</c> is evaluated after
1138
an exception in <c>Exprs</c>, <c>Body</c> or <c>ExceptionBody</c>,
1139
that exception is lost and masked by the exception in
1140
<c>AfterBody</c>.</p>
1141
<p>The <c>of</c>, <c>catch</c> and <c>after</c> sections are all
1142
optional, as long as there is at least a <c>catch</c> or an
1143
<c>after</c> section, so the following are valid <c>try</c>
1147
Pattern when GuardSeq ->
1155
ExpressionPattern ->
1161
try Exprs after AfterBody end</code>
1162
<p>Example of using <c>after</c>, this code will close the file
1163
even in the event of exceptions in <c>file:read/2</c> or in
1164
<c>binary_to_term/1</c>, and exceptions will be the same as
1165
without the <c>try</c>...<c>after</c>...<c>end</c> expression:</p>
1167
termize_file(Name) ->
1168
{ok,F} = file:open(Name, [read,binary]),
1170
{ok,Bin} = file:read(F, 1024*1024),
1175
<p>Example: Using <c>try</c> to emulate <c>catch Expr</c>.</p>
1180
exit:Reason -> {'EXIT',Reason}
1181
error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}}
1186
<title>Parenthesized Expressions</title>
1189
<p>Parenthesized expressions are useful to override
1190
<seealso marker="#prec">operator precedences</seealso>,
1191
for example in arithmetic expressions:</p>
1193
1> <input>1 + 2 * 3.</input>
1195
2> <input>(1 + 2) * 3.</input>
1200
<title>Block Expressions</title>
1207
<p>Block expressions provide a way to group a sequence of
1208
expressions, similar to a clause body. The return value is
1209
the value of the last expression <c>ExprN</c>.</p>
1213
<marker id="lcs"></marker>
1214
<title>List Comprehensions</title>
1215
<p>List comprehensions are a feature of many modern functional
1216
programming languages. Subject to certain rules, they provide a
1217
succinct notation for generating elements in a list.</p>
1218
<p>List comprehensions are analogous to set comprehensions in
1219
Zermelo-Frankel set theory and are called ZF expressions in
1220
Miranda. They are analogous to the <c>setof</c> and
1221
<c>findall</c> predicates in Prolog.</p>
1222
<p>List comprehensions are written with the following syntax:</p>
1224
[Expr || Qualifier1,...,QualifierN]</pre>
1225
<p><c>Expr</c> is an arbitrary expression, and each
1226
<c>Qualifier</c> is either a generator or a filter.</p>
1227
<list type="bulleted">
1228
<item>A <em>generator</em> is written as: <br></br>
1230
<c><![CDATA[Pattern <- ListExpr]]></c>. <br></br>
1231
<c>ListExpr</c> must be an expression which evaluates to a
1232
list of terms.</item>
1233
<item>A <em>bit string generator</em> is written as: <br></br>
1235
<c><![CDATA[BitstringPattern <= BitStringExpr]]></c>. <br></br>
1236
<c>BitStringExpr</c> must be an expression which evaluates to a
1238
<item>A <em>filter</em> is an expression which evaluates to
1239
<c>true</c> or <c>false</c>.</item>
1241
<p>The variables in the generator patterns shadow variables in the function
1242
clause surrounding the list comprehensions.</p> <p>A list comprehension
1243
returns a list, where the elements are the result of evaluating <c>Expr</c>
1244
for each combination of generator list elements and bit string generator
1245
elements for which all filters are true.</p> <p></p> <p>Example:</p>
1247
1> <input>[X*2 || X <- [1,2,3]].</input>
1249
<p>More examples can be found in <em>Programming Examples</em>.</p>
1255
<title>Bit String Comprehensions</title>
1257
<p>Bit string comprehensions are
1258
analogous to List Comprehensions. They are used to generate bit strings
1259
efficiently and succinctly.</p>
1260
<p>Bit string comprehensions are written with
1261
the following syntax:</p>
1263
<< BitString || Qualifier1,...,QualifierN >></pre>
1264
<p><c>BitString</c> is a bit string expression, and each
1265
<c>Qualifier</c> is either a generator, a bit string generator or a filter.</p>
1266
<list type="bulleted">
1267
<item>A <em>generator</em> is written as: <br></br>
1268
<c><![CDATA[Pattern <- ListExpr]]></c>. <br></br>
1269
<c>ListExpr</c> must be an expression which evaluates to a
1270
list of terms.</item>
1271
<item>A <em>bit string generator</em> is written as: <br></br>
1273
<c><![CDATA[BitstringPattern <= BitStringExpr]]></c>. <br></br>
1274
<c>BitStringExpr</c> must be an expression which evaluates to a
1276
<item>A <em>filter</em> is an expression which evaluates to
1277
<c>true</c> or <c>false</c>.</item>
1279
<p>The variables in the generator patterns shadow variables in
1280
the function clause surrounding the bit string comprehensions.</p>
1281
<p>A bit string comprehension returns a bit string, which is
1282
created by concatenating the results of evaluating <c>BitString</c>
1283
for each combination of bit string generator elements for which all
1284
filters are true.</p>
1288
1> <input><< << (X*2) >> ||
1289
<<X>> <= << 1,2,3 >> >>.</input>
1290
<<2,4,6>></pre>
1291
<p>More examples can be found in <em>Programming Examples</em>.</p>
1295
<marker id="guards"></marker>
1296
<title>Guard Sequences</title>
1298
<p>A <em>guard sequence</em> is a sequence of guards, separated
1299
by semicolon (;). The guard sequence is true if at least one of
1300
the guards is true. (The remaining guards, if any, will not be
1301
evaluated.)<br></br>
1302
<c>Guard1;...;GuardK</c></p>
1303
<p>A <em>guard</em> is a sequence of guard expressions, separated
1304
by comma (,). The guard is true if all guard expressions
1305
evaluate to <c>true</c>.<br></br>
1306
<c>GuardExpr1,...,GuardExprN</c></p>
1307
<p>The set of valid <em>guard expressions</em> (sometimes called
1308
guard tests) is a subset of the set of valid Erlang expressions.
1309
The reason for restricting the set of valid expressions is that
1310
evaluation of a guard expression must be guaranteed to be free
1311
of side effects. Valid guard expressions are:</p>
1312
<list type="bulleted">
1313
<item>the atom <c>true</c>,</item>
1314
<item>other constants (terms and bound variables), all regarded
1316
<item>calls to the BIFs specified below,</item>
1317
<item>term comparisons,</item>
1318
<item>arithmetic expressions,</item>
1319
<item>boolean expressions, and</item>
1320
<item>short-circuit expressions (<c>andalso</c>/<c>orelse</c>).</item>
1324
<cell align="left" valign="middle"><c>is_atom/1</c></cell>
1327
<cell align="left" valign="middle"><c>is_binary/1</c></cell>
1330
<cell align="left" valign="middle"><c>is_bitstring/1</c></cell>
1333
<cell align="left" valign="middle"><c>is_boolean/1</c></cell>
1336
<cell align="left" valign="middle"><c>is_float/1</c></cell>
1339
<cell align="left" valign="middle"><c>is_function/1</c></cell>
1342
<cell align="left" valign="middle"><c>is_function/2</c></cell>
1345
<cell align="left" valign="middle"><c>is_integer/1</c></cell>
1348
<cell align="left" valign="middle"><c>is_list/1</c></cell>
1351
<cell align="left" valign="middle"><c>is_number/1</c></cell>
1354
<cell align="left" valign="middle"><c>is_pid/1</c></cell>
1357
<cell align="left" valign="middle"><c>is_port/1</c></cell>
1360
<cell align="left" valign="middle"><c>is_record/2</c></cell>
1363
<cell align="left" valign="middle"><c>is_record/3</c></cell>
1366
<cell align="left" valign="middle"><c>is_reference/1</c></cell>
1369
<cell align="left" valign="middle"><c>is_tuple/1</c></cell>
1371
<tcaption>Type Test BIFs.</tcaption>
1373
<p>Note that most type test BIFs have older equivalents, without
1374
the <c>is_</c> prefix. These old BIFs are retained for backwards
1375
compatibility only and should not be used in new code. They are
1376
also only allowed at top level. For example, they are not allowed
1377
in boolean expressions in guards.</p>
1380
<cell align="left" valign="middle"><c>abs(Number)</c></cell>
1383
<cell align="left" valign="middle"><c>bit_size(Bitstring)</c></cell>
1386
<cell align="left" valign="middle"><c>byte_size(Bitstring)</c></cell>
1389
<cell align="left" valign="middle"><c>element(N, Tuple)</c></cell>
1392
<cell align="left" valign="middle"><c>float(Term)</c></cell>
1395
<cell align="left" valign="middle"><c>hd(List)</c></cell>
1398
<cell align="left" valign="middle"><c>length(List)</c></cell>
1401
<cell align="left" valign="middle"><c>node()</c></cell>
1404
<cell align="left" valign="middle"><c>node(Pid|Ref|Port)</c></cell>
1407
<cell align="left" valign="middle"><c>round(Number)</c></cell>
1410
<cell align="left" valign="middle"><c>self()</c></cell>
1413
<cell align="left" valign="middle"><c>size(Tuple|Bitstring)</c></cell>
1416
<cell align="left" valign="middle"><c>tl(List)</c></cell>
1419
<cell align="left" valign="middle"><c>trunc(Number)</c></cell>
1422
<cell align="left" valign="middle"><c>tuple_size(Tuple)</c></cell>
1424
<tcaption>Other BIFs Allowed in Guard Expressions.</tcaption>
1427
<p>If an arithmetic expression, a boolean expression, a
1428
short-circuit expression, or a call to a guard BIF fails (because
1429
of invalid arguments), the entire guard fails. If the guard was
1430
part of a guard sequence, the next guard in the sequence (that is,
1431
the guard following the next semicolon) will be evaluated.</p>
1436
<marker id="prec"></marker>
1437
<title>Operator Precedence</title>
1438
<p>Operator precedence in falling priority:</p>
1441
<cell align="left" valign="middle">:</cell>
1442
<cell align="left" valign="middle"> </cell>
1445
<cell align="left" valign="middle">#</cell>
1446
<cell align="left" valign="middle"> </cell>
1449
<cell align="left" valign="middle">Unary + - bnot not</cell>
1450
<cell align="left" valign="middle"> </cell>
1453
<cell align="left" valign="middle">/ * div rem band and</cell>
1454
<cell align="left" valign="middle">Left associative</cell>
1457
<cell align="left" valign="middle">+ - bor bxor bsl bsr or xor</cell>
1458
<cell align="left" valign="middle">Left associative</cell>
1461
<cell align="left" valign="middle">++ --</cell>
1462
<cell align="left" valign="middle">Right associative</cell>
1465
<cell align="left" valign="middle">== /= =< < >= > =:= =/=</cell>
1466
<cell align="left" valign="middle"> </cell>
1469
<cell align="left" valign="middle">andalso</cell>
1470
<cell align="left" valign="middle"> </cell>
1473
<cell align="left" valign="middle">orelse</cell>
1474
<cell align="left" valign="middle"> </cell>
1477
<cell align="left" valign="middle">= !</cell>
1478
<cell align="left" valign="middle">Right associative</cell>
1481
<cell align="left" valign="middle">catch</cell>
1482
<cell align="left" valign="middle"> </cell>
1484
<tcaption>Operator Precedence.</tcaption>
1486
<p>When evaluating an expression, the operator with the highest
1487
priority is evaluated first. Operators with the same priority
1488
are evaluated according to their associativity. Example:
1489
The left associative arithmetic operators are evaluated left to
1492
<input>6 + 5 * 4 - 3 / 2</input> evaluates to
1493
<input>6 + 20 - 1.5</input> evaluates to
1494
<input>26 - 1.5</input> evaluates to
1495
<input>24.5</input></pre>