~ubuntu-branches/ubuntu/trusty/erlang/trusty

« back to all changes in this revision

Viewing changes to system/doc/reference_manual/expressions.xml

  • Committer: Bazaar Package Importer
  • Author(s): Clint Byrum
  • Date: 2011-05-05 15:48:43 UTC
  • mfrom: (3.5.13 sid)
  • Revision ID: james.westby@ubuntu.com-20110505154843-0om6ekzg6m7ugj27
Tags: 1:14.b.2-dfsg-3ubuntu1
* Merge from debian unstable.  Remaining changes:
  - Drop libwxgtk2.8-dev build dependency. Wx isn't in main, and not
    supposed to.
  - Drop erlang-wx binary.
  - Drop erlang-wx dependency from -megaco, -common-test, and -reltool, they
    do not really need wx. Also drop it from -debugger; the GUI needs wx,
    but it apparently has CLI bits as well, and is also needed by -megaco,
    so let's keep the package for now.
  - debian/patches/series: Do what I meant, and enable build-options.patch
    instead.
* Additional changes:
  - Drop erlang-wx from -et
* Dropped Changes:
  - patches/pcre-crash.patch: CVE-2008-2371: outer level option with
    alternatives caused crash. (Applied Upstream)
  - fix for ssl certificate verification in newSSL: 
    ssl_cacertfile_fix.patch (Applied Upstream)
  - debian/patches/series: Enable native.patch again, to get stripped beam
    files and reduce the package size again. (build-options is what
    actually accomplished this)
  - Remove build-options.patch on advice from upstream and because it caused
    odd build failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?xml version="1.0" encoding="latin1" ?>
 
2
<!DOCTYPE chapter SYSTEM "chapter.dtd">
 
3
 
 
4
<chapter>
 
5
  <header>
 
6
    <copyright>
 
7
      <year>2003</year><year>2011</year>
 
8
      <holder>Ericsson AB. All Rights Reserved.</holder>
 
9
    </copyright>
 
10
    <legalnotice>
 
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/.
 
16
 
 
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
 
20
      under the License.
 
21
 
 
22
    </legalnotice>
 
23
 
 
24
    <title>Expressions</title>
 
25
    <prepared></prepared>
 
26
    <docno></docno>
 
27
    <date></date>
 
28
    <rev></rev>
 
29
    <file>expressions.xml</file>
 
30
  </header>
 
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>
 
38
 
 
39
  <section>
 
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>
 
44
    <code type="none">
 
45
Expr1 + Expr2</code>
 
46
    <p><c>Expr1</c> and <c>Expr2</c>, which are also expressions, are
 
47
      evaluated first - in any order - before the addition is
 
48
      performed.</p>
 
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>
 
53
  </section>
 
54
 
 
55
  <section>
 
56
    <marker id="term"></marker>
 
57
    <title>Terms</title>
 
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>
 
61
  </section>
 
62
 
 
63
  <section>
 
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 @.
 
70
      Examples:</p>
 
71
    <pre>
 
72
X
 
73
Name1
 
74
PhoneNumber
 
75
Phone_number
 
76
_
 
77
_Height</pre>
 
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
 
81
      once.</p>
 
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
 
84
      ignored. Example:</p>
 
85
    <pre>
 
86
[H|_] = [1,2,3]</pre>
 
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
 
91
      code</p>
 
92
    <pre>
 
93
member(_, []) ->
 
94
    [].</pre>
 
95
    <p>can be rewritten to be more readable:</p>
 
96
    <pre>
 
97
member(Elem, []) ->
 
98
    [].</pre>
 
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
 
102
      to:</p>
 
103
    <pre>
 
104
member(_Elem, []) ->
 
105
    [].</pre>
 
106
    <p>Note that since variables starting with an underscore are
 
107
      not anonymous, this will match:</p>
 
108
    <pre>
 
109
{_,_} = {1,2}</pre>
 
110
    <p>But this will fail:</p>
 
111
    <pre>
 
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>
 
122
  </section>
 
123
 
 
124
  <section>
 
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>
 
129
    <pre>
 
130
Name1
 
131
[H|T]
 
132
{error,Reason}</pre>
 
133
    <p>Patterns are allowed in clause heads, <c>case</c> and
 
134
      <c>receive</c> expressions, and match expressions.</p>
 
135
 
 
136
    <section>
 
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>
 
140
      <pre>
 
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.
 
145
        Example:</p>
 
146
      <pre>
 
147
f({connect,From,To,Number,Options}, To) ->
 
148
    Signal = {connect,From,To,Number,Options},
 
149
    ...;
 
150
f(Signal, To) ->
 
151
    ignore.</pre>
 
152
      <p>can instead be written as</p>
 
153
      <pre>
 
154
f({connect,_,To,_,_} = Signal, To) ->
 
155
    ...;
 
156
f(Signal, To) ->
 
157
    ignore.</pre>
 
158
    </section>
 
159
 
 
160
    <section>
 
161
      <title>String Prefix in Patterns</title>
 
162
      <p>When matching strings, the following is a valid pattern:</p>
 
163
      <pre>
 
164
f("prefix" ++ Str) -> ...</pre>
 
165
      <p>This is syntactic sugar for the equivalent, but harder to
 
166
        read</p>
 
167
      <pre>
 
168
f([$p,$r,$e,$f,$i,$x | Str]) -> ...</pre>
 
169
    </section>
 
170
 
 
171
    <section>
 
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>
 
176
      <pre>
 
177
case {Value, Result} of
 
178
    {?THRESHOLD+1, ok} -> ...</pre>
 
179
      <p>This feature was added in Erlang 5.0/OTP R7.</p>
 
180
    </section>
 
181
  </section>
 
182
 
 
183
  <section>
 
184
    <title>Match</title>
 
185
    <pre>
 
186
Expr1 = Expr2</pre>
 
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
 
191
      occur.</p>
 
192
    <p>Examples:</p>
 
193
    <pre>
 
194
1> <input>{A, B} = {answer, 42}.</input>
 
195
{answer,42}
 
196
2> <input>A.</input>
 
197
answer
 
198
3> <input>{C, D} = [1, 2].</input>
 
199
** exception error: no match of right hand side value [1,2]</pre>
 
200
  </section>
 
201
 
 
202
  <section>
 
203
    <marker id="calls"></marker>
 
204
    <title>Function Calls</title>
 
205
    <pre>
 
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>.
 
214
      Example:</p>
 
215
    <code type="none">
 
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>
 
220
 
 
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>
 
229
 
 
230
    <code type="none">
 
231
handle(Msg, State)
 
232
spawn(m, init, [])</code>
 
233
    <p>Examples where ExprF is a fun:</p>
 
234
    <code type="none">
 
235
Fun1 = fun(X) -> X+1 end
 
236
Fun1(3)
 
237
=> 4
 
238
 
 
239
Fun2 = {lists,append}
 
240
Fun2([1,2], [3,4])
 
241
=> [1,2,3,4]
 
242
 
 
243
fun lists:append/2([1,2], [3,4])
 
244
=> [1,2,3,4]</code>
 
245
 
 
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>
 
250
 
 
251
    <p>See also the chapter about
 
252
      <seealso marker="functions#eval">Function Evaluation</seealso>.</p>
 
253
 
 
254
    <section>
 
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
 
262
    is mandatory.</p>
 
263
 
 
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
 
270
    of old code.</p>
 
271
 
 
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>
 
281
 
 
282
    <code type="none">
 
283
-export([length/1,f/1]).
 
284
 
 
285
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
 
286
 
 
287
length([]) ->
 
288
    0;
 
289
length([H|T]) ->
 
290
    1 + length(T). %% Calls the local funtion length/1
 
291
 
 
292
f(X) when erlang:length(X) > 3 -> %% Calls erlang:length/1,
 
293
                                  %% which is allowed in guards
 
294
    long.</code>
 
295
 
 
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>
 
300
 
 
301
    <code type="none">
 
302
-export([f/1]).
 
303
 
 
304
-compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported
 
305
 
 
306
-import(mod,[length/1]).
 
307
 
 
308
f(X) when erlang:length(X) > 33 -> %% Calls erlang:lenght/1,
 
309
                                   %% which is allowed in guards
 
310
 
 
311
    erlang:length(X);              %% Explicit call to erlang:length in body
 
312
 
 
313
f(X) ->
 
314
    length(X).                     %% mod:length/1 is called</code>
 
315
 
 
316
 
 
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
 
322
    function name.</p>
 
323
    </section>
 
324
  </section>
 
325
 
 
326
  <section>
 
327
    <title>If</title>
 
328
    <pre>
 
329
if
 
330
    GuardSeq1 ->
 
331
        Body1;
 
332
    ...;
 
333
    GuardSeqN ->
 
334
        BodyN
 
335
end</pre>
 
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>
 
345
    <p>Example:</p>
 
346
    <pre>
 
347
is_greater_than(X, Y) ->
 
348
    if
 
349
        X>Y ->
 
350
            true;
 
351
        true -> % works as an 'else' branch
 
352
            false
 
353
    end</pre>
 
354
  </section>
 
355
 
 
356
  <section>
 
357
    <marker id="case"></marker>
 
358
    <title>Case</title>
 
359
    <pre>
 
360
case Expr of
 
361
    Pattern1 [when GuardSeq1] ->
 
362
        Body1;
 
363
    ...;
 
364
    PatternN [when GuardSeqN] ->
 
365
        BodyN
 
366
end</pre>
 
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>
 
375
    <p>Example:</p>
 
376
    <pre>
 
377
is_valid_signal(Signal) ->
 
378
    case Signal of
 
379
        {signal, _What, _From, _To} ->
 
380
            true;
 
381
        {signal, _What, _To} ->
 
382
            true;
 
383
        _Else ->
 
384
            false
 
385
    end.</pre>
 
386
  </section>
 
387
 
 
388
  <section>
 
389
    <marker id="send"></marker>
 
390
    <title>Send</title>
 
391
    <pre>
 
392
Expr1 ! Expr2</pre>
 
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>
 
407
    </list>
 
408
  </section>
 
409
 
 
410
  <section>
 
411
    <marker id="receive"></marker>
 
412
    <title>Receive</title>
 
413
    <pre>
 
414
receive
 
415
    Pattern1 [when GuardSeq1] ->
 
416
        Body1;
 
417
    ...;
 
418
    PatternN [when GuardSeqN] ->
 
419
        BodyN
 
420
end</pre>
 
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>
 
434
    <p>Example:</p>
 
435
    <pre>
 
436
wait_for_onhook() ->
 
437
    receive
 
438
        onhook ->
 
439
            disconnect(),
 
440
            idle();
 
441
        {connect, B} ->
 
442
            B ! {busy, self()},
 
443
            wait_for_onhook()
 
444
    end.</pre>
 
445
    <p>It is possible to augment the <c>receive</c> expression with a
 
446
      timeout:</p>
 
447
    <pre>
 
448
receive
 
449
    Pattern1 [when GuardSeq1] ->
 
450
        Body1;
 
451
    ...;
 
452
    PatternN [when GuardSeqN] ->
 
453
        BodyN
 
454
after
 
455
    ExprT ->
 
456
        BodyT
 
457
end</pre>
 
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>
 
464
      expression.</p>
 
465
    <p>Example:</p>
 
466
    <pre>
 
467
wait_for_onhook() ->
 
468
    receive
 
469
        onhook ->
 
470
            disconnect(),
 
471
            idle();
 
472
        {connect, B} ->
 
473
            B ! {busy, self()},
 
474
            wait_for_onhook()
 
475
    after
 
476
        60000 ->
 
477
            disconnect(),
 
478
            error()
 
479
    end.</pre>
 
480
    <p>It is legal to use a <c>receive..after</c> expression with no
 
481
      branches:</p>
 
482
    <pre>
 
483
receive
 
484
after
 
485
    ExprT ->
 
486
        BodyT
 
487
end</pre>
 
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>
 
491
    <p>Example:</p>
 
492
    <pre>
 
493
timer() ->
 
494
    spawn(m, timer, [self()]).
 
495
 
 
496
timer(Pid) ->
 
497
    receive
 
498
    after
 
499
        5000 ->
 
500
            Pid ! timeout
 
501
    end.</pre>
 
502
    <p>There are two special cases for the timeout value <c>ExprT</c>:</p>
 
503
    <taglist>
 
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>
 
508
      <tag>0</tag>
 
509
      <item>If there is no matching message in the mailbox, the timeout
 
510
       will occur immediately.</item>
 
511
    </taglist>
 
512
  </section>
 
513
 
 
514
  <section>
 
515
    <title>Term Comparisons</title>
 
516
    <pre>
 
517
Expr1 <input>op</input> Expr2</pre>
 
518
    <table>
 
519
      <row>
 
520
        <cell align="left" valign="middle"><em>op</em></cell>
 
521
        <cell align="left" valign="middle"><em>Description</em></cell>
 
522
      </row>
 
523
      <row>
 
524
        <cell align="left" valign="middle">==</cell>
 
525
        <cell align="left" valign="middle">equal to</cell>
 
526
      </row>
 
527
      <row>
 
528
        <cell align="left" valign="middle">/=</cell>
 
529
        <cell align="left" valign="middle">not equal to</cell>
 
530
      </row>
 
531
      <row>
 
532
        <cell align="left" valign="middle">=&lt;</cell>
 
533
        <cell align="left" valign="middle">less than or equal to</cell>
 
534
      </row>
 
535
      <row>
 
536
        <cell align="left" valign="middle">&lt;</cell>
 
537
        <cell align="left" valign="middle">less than</cell>
 
538
      </row>
 
539
      <row>
 
540
        <cell align="left" valign="middle">&gt;=</cell>
 
541
        <cell align="left" valign="middle">greater than or equal to</cell>
 
542
      </row>
 
543
      <row>
 
544
        <cell align="left" valign="middle">&gt;</cell>
 
545
        <cell align="left" valign="middle">greater than</cell>
 
546
      </row>
 
547
      <row>
 
548
        <cell align="left" valign="middle">=:=</cell>
 
549
        <cell align="left" valign="middle">exactly equal to</cell>
 
550
      </row>
 
551
      <row>
 
552
        <cell align="left" valign="middle">=/=</cell>
 
553
        <cell align="left" valign="middle">exactly not equal to</cell>
 
554
      </row>
 
555
      <tcaption>Term Comparison Operators.</tcaption>
 
556
    </table>
 
557
    <p>The arguments may be of different data types. The following
 
558
      order is defined:</p>
 
559
    <pre>
 
560
number &lt; atom &lt; reference &lt; fun &lt; port &lt; pid &lt; tuple &lt; list &lt; 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
 
563
      element.</p>
 
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
 
570
      <c>false</c>.</p>
 
571
    <p>Examples:</p>
 
572
    <pre>
 
573
1> <input>1==1.0.</input>
 
574
true
 
575
2> <input>1=:=1.0.</input>
 
576
false
 
577
3> <input>1 > a.</input>
 
578
false</pre>
 
579
  </section>
 
580
 
 
581
  <section>
 
582
    <title>Arithmetic Expressions</title>
 
583
    <pre>
 
584
<input>op</input> Expr
 
585
Expr1 <input>op</input> Expr2</pre>
 
586
    <table>
 
587
      <row>
 
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>
 
591
      </row>
 
592
      <row>
 
593
        <cell align="left" valign="middle">+</cell>
 
594
        <cell align="left" valign="middle">unary +</cell>
 
595
        <cell align="left" valign="middle">number</cell>
 
596
      </row>
 
597
      <row>
 
598
        <cell align="left" valign="middle">-</cell>
 
599
        <cell align="left" valign="middle">unary -</cell>
 
600
        <cell align="left" valign="middle">number</cell>
 
601
      </row>
 
602
      <row>
 
603
        <cell align="left" valign="middle">+</cell>
 
604
        <cell align="left" valign="middle">&nbsp;</cell>
 
605
        <cell align="left" valign="middle">number</cell>
 
606
      </row>
 
607
      <row>
 
608
        <cell align="left" valign="middle">-</cell>
 
609
        <cell align="left" valign="middle">&nbsp;</cell>
 
610
        <cell align="left" valign="middle">number</cell>
 
611
      </row>
 
612
      <row>
 
613
        <cell align="left" valign="middle">*</cell>
 
614
        <cell align="left" valign="middle">&nbsp;</cell>
 
615
        <cell align="left" valign="middle">number</cell>
 
616
      </row>
 
617
      <row>
 
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>
 
621
      </row>
 
622
      <row>
 
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>
 
626
      </row>
 
627
      <row>
 
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>
 
631
      </row>
 
632
      <row>
 
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>
 
636
      </row>
 
637
      <row>
 
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>
 
641
      </row>
 
642
      <row>
 
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>
 
646
      </row>
 
647
      <row>
 
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>
 
651
      </row>
 
652
      <row>
 
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>
 
656
      </row>
 
657
      <row>
 
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>
 
661
      </row>
 
662
      <tcaption>Arithmetic Operators.</tcaption>
 
663
    </table>
 
664
 
 
665
    <p>Examples:</p>
 
666
    <pre>
 
667
1> <input>+1.</input>
 
668
1
 
669
2> <input>-1.</input>
 
670
-1
 
671
3> <input>1+1.</input>
 
672
2
 
673
4> <input>4/2.</input>
 
674
2.0
 
675
5> <input>5 div 2.</input>
 
676
2
 
677
6> <input>5 rem 2.</input>
 
678
1
 
679
7> <input>2#10 band 2#01.</input>
 
680
0
 
681
8> <input>2#10 bor 2#01.</input>
 
682
3
 
683
9> <input>a + 10.</input>
 
684
** exception error: bad argument in an arithmetic expression
 
685
     in operator  +/2
 
686
        called as a + 10
 
687
10> <input>1 bsl (1 bsl 64).</input>
 
688
** exception error: a system limit has been reached
 
689
     in operator  bsl/2
 
690
        called as 1 bsl 18446744073709551616</pre>
 
691
  </section>
 
692
 
 
693
  <section>
 
694
    <title>Boolean Expressions</title>
 
695
    <pre>
 
696
<input>op</input> Expr
 
697
Expr1 <input>op</input> Expr2</pre>
 
698
    <table>
 
699
      <row>
 
700
        <cell align="left" valign="middle"><em>op</em></cell>
 
701
        <cell align="left" valign="middle"><em>Description</em></cell>
 
702
      </row>
 
703
      <row>
 
704
        <cell align="left" valign="middle">not</cell>
 
705
        <cell align="left" valign="middle">unary logical not</cell>
 
706
      </row>
 
707
      <row>
 
708
        <cell align="left" valign="middle">and</cell>
 
709
        <cell align="left" valign="middle">logical and</cell>
 
710
      </row>
 
711
      <row>
 
712
        <cell align="left" valign="middle">or</cell>
 
713
        <cell align="left" valign="middle">logical or</cell>
 
714
      </row>
 
715
      <row>
 
716
        <cell align="left" valign="middle">xor</cell>
 
717
        <cell align="left" valign="middle">logical xor</cell>
 
718
      </row>
 
719
      <tcaption>Logical Operators.</tcaption>
 
720
    </table>
 
721
    <p>Examples:</p>
 
722
    <pre>
 
723
1> <input>not true.</input>
 
724
false
 
725
2> <input>true and false.</input>
 
726
false
 
727
3> <input>true xor false.</input>
 
728
true
 
729
4> <input>true or garbage.</input>
 
730
** exception error: bad argument
 
731
     in operator  or/2
 
732
        called as true or garbage</pre>
 
733
  </section>
 
734
 
 
735
  <section>
 
736
    <title>Short-Circuit Expressions</title>
 
737
    <pre>
 
738
Expr1 orelse Expr2
 
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>
 
747
 
 
748
    <p>Example 1:</p>
 
749
    <pre>
 
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>
 
753
    <p>Example 2:</p>
 
754
    <pre>
 
755
OnlyOne = is_atom(L) orelse
 
756
         (is_list(L) andalso length(L) == 1),</pre>
 
757
 
 
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>
 
762
 
 
763
    <pre>
 
764
all(Pred, [Hd|Tail]) ->
 
765
    Pred(Hd) andalso all(Pred, Tail);
 
766
all(_, []) ->
 
767
    true.</pre>
 
768
  </section>
 
769
 
 
770
  <section>
 
771
    <title>List Operations</title>
 
772
    <pre>
 
773
Expr1 ++ Expr2
 
774
Expr1 -- Expr2</pre>
 
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>
 
781
    <p>Example:</p>
 
782
    <pre>
 
783
1> <input>[1,2,3]++[4,5].</input>
 
784
[1,2,3,4,5]
 
785
2> <input>[1,2,3,2,1,2]--[2,1,2].</input>
 
786
[3,1,2]</pre>
 
787
 
 
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>
 
792
   </section>
 
793
 
 
794
  <section>
 
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>
 
802
    <pre>
 
803
Ei = Value |
 
804
     Value:Size |
 
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>
 
811
 
 
812
    <p>Used in a bit string matching, <c>Value</c> must be a variable,
 
813
    or an integer, float or string.</p>
 
814
 
 
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>
 
818
 
 
819
    <p>Used in a bit string construction, <c>Size</c> is an expression
 
820
    which should evaluate to an integer.</p>
 
821
    
 
822
    <p>Used in a bit string matching, <c>Size</c> must be an integer or a 
 
823
    variable bound to an integer.</p>
 
824
 
 
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>
 
832
 
 
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>
 
836
    
 
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>
 
840
    <taglist>
 
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.
 
847
      </item>
 
848
 
 
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>
 
852
 
 
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>.
 
859
       </item>
 
860
 
 
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>.
 
866
       </item>
 
867
    </taglist>
 
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>
 
871
 
 
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>
 
876
 
 
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>
 
880
 
 
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>
 
892
 
 
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>
 
897
 
 
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>
 
903
 
 
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>
 
907
 
 
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>
 
912
 
 
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
 
916
    mentioned above.</p>
 
917
 
 
918
    <p>Examples:</p>
 
919
    <pre>
 
920
1> <input>Bin1 = &lt;&lt;1,17,42&gt;&gt;.</input>
 
921
&lt;&lt;1,17,42&gt;&gt;
 
922
2> <input>Bin2 = &lt;&lt;"abc"&gt;&gt;.</input>
 
923
&lt;&lt;97,98,99&gt;&gt;
 
924
3> <input>Bin3 = &lt;&lt;1,17,42:16&gt;&gt;.</input>
 
925
&lt;&lt;1,17,0,42&gt;&gt;
 
926
4> <input>&lt;&lt;A,B,C:16&gt;&gt; = &lt;&lt;1,17,42:16&gt;&gt;.</input>
 
927
&lt;&lt;1,17,0,42&gt;&gt;
 
928
5> <input>C.</input>
 
929
42
 
930
6> <input>&lt;&lt;D:16,E,F&gt;&gt; = &lt;&lt;1,17,42:16&gt;&gt;.</input>
 
931
&lt;&lt;1,17,0,42&gt;&gt;
 
932
7> <input>D.</input>
 
933
273
 
934
8> <input>F.</input>
 
935
42
 
936
9> <input>&lt;&lt;G,H/binary&gt;&gt; = &lt;&lt;1,17,42:16&gt;&gt;.</input>
 
937
&lt;&lt;1,17,0,42&gt;&gt;
 
938
10> <input>H.</input>
 
939
&lt;&lt;17,0,42&gt;&gt;
 
940
11> <input>&lt;&lt;G,H/bitstring&gt;&gt; = &lt;&lt;1,17,42:12&gt;&gt;.</input>
 
941
&lt;&lt;1,17,1,10:4&gt;&gt;
 
942
12> <input>H.</input>
 
943
&lt;&lt;17,1,10:4&gt;&gt;
 
944
13> <input>&lt;&lt;1024/utf8&gt;&gt;.</input>
 
945
&lt;&lt;208,128&gt;&gt;
 
946
</pre>
 
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>
 
952
  </section>
 
953
 
 
954
  <section>
 
955
    <marker id="funs"></marker>
 
956
    <title>Fun Expressions</title>
 
957
    <pre>
 
958
fun
 
959
    (Pattern11,...,Pattern1N) [when GuardSeq1] ->
 
960
        Body1;
 
961
    ...;
 
962
    (PatternK1,...,PatternKN) [when GuardSeqK] ->
 
963
        BodyK
 
964
end</pre>
 
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
 
969
      specified.</p>
 
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>
 
974
    <p>Examples:</p>
 
975
    <pre>
 
976
1> <input>Fun1 = fun (X) -> X+1 end.</input>
 
977
#Fun&lt;erl_eval.6.39074546&gt;
 
978
2> <input>Fun1(2).</input>
 
979
3
 
980
3> <input>Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.</input>
 
981
#Fun&lt;erl_eval.6.39074546&gt;
 
982
4> <input>Fun2(7).</input>
 
983
gt</pre>
 
984
    <p>The following fun expressions are also allowed:</p>
 
985
    <pre>
 
986
fun Name/Arity
 
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>
 
991
    <pre>
 
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>.
 
997
      </p>
 
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>
 
1005
  </section>
 
1006
 
 
1007
  <section>
 
1008
    <marker id="catch"></marker>
 
1009
    <title>Catch and Throw</title>
 
1010
    <code type="none">
 
1011
catch Expr</code>
 
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>
 
1023
    <p>Examples:</p>
 
1024
    <p></p>
 
1025
    <pre>
 
1026
1> <input>catch 1+2.</input>
 
1027
3
 
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>
 
1033
    <pre>
 
1034
3> <input>A = catch 1+2.</input>
 
1035
** 1: syntax error before: 'catch' **
 
1036
4> <input>A = (catch 1+2).</input>
 
1037
3</pre>
 
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>
 
1041
    <pre>
 
1042
5> <input>catch throw(hello).</input>
 
1043
hello</pre>
 
1044
    <p>If <c>throw/1</c> is not evaluated within a catch, a
 
1045
      <c>nocatch</c> run-time error will occur.</p>
 
1046
  </section>
 
1047
 
 
1048
  <section>
 
1049
    <marker id="try"></marker>
 
1050
    <title>Try</title>
 
1051
    <code type="none">
 
1052
try Exprs
 
1053
catch
 
1054
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
 
1055
        ExceptionBody1;
 
1056
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
 
1057
        ExceptionBodyN
 
1058
end</code>
 
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>
 
1081
      expression.</p>
 
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>
 
1085
      section:
 
1086
      </p>
 
1087
    <code type="none">
 
1088
try Exprs of
 
1089
    Pattern1 [when GuardSeq1] ->
 
1090
        Body1;
 
1091
    ...;
 
1092
    PatternN [when GuardSeqN] ->
 
1093
        BodyN
 
1094
catch
 
1095
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
 
1096
        ExceptionBody1;
 
1097
    ...;
 
1098
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
 
1099
        ExceptionBodyN
 
1100
end</code>
 
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
 
1107
      not caught.</p>
 
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
 
1110
      effects:</p>
 
1111
    <code type="none">
 
1112
try Exprs of
 
1113
    Pattern1 [when GuardSeq1] ->
 
1114
        Body1;
 
1115
    ...;
 
1116
    PatternN [when GuardSeqN] ->
 
1117
        BodyN
 
1118
catch
 
1119
    [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] ->
 
1120
        ExceptionBody1;
 
1121
    ...;
 
1122
    [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] ->
 
1123
        ExceptionBodyN
 
1124
after
 
1125
    AfterBody
 
1126
end</code>
 
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>
 
1144
      expressions:</p>
 
1145
    <code type="none">
 
1146
try Exprs of 
 
1147
    Pattern when GuardSeq -> 
 
1148
        Body 
 
1149
after 
 
1150
    AfterBody 
 
1151
end
 
1152
 
 
1153
try Exprs
 
1154
catch 
 
1155
    ExpressionPattern -> 
 
1156
        ExpressionBody
 
1157
after
 
1158
    AfterBody
 
1159
end
 
1160
 
 
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>
 
1166
    <code type="none">
 
1167
termize_file(Name) ->
 
1168
    {ok,F} = file:open(Name, [read,binary]),
 
1169
    try
 
1170
        {ok,Bin} = file:read(F, 1024*1024),
 
1171
        binary_to_term(Bin)
 
1172
    after
 
1173
        file:close(F)
 
1174
    end.</code>
 
1175
    <p>Example: Using <c>try</c> to emulate <c>catch Expr</c>.</p>
 
1176
    <code type="none">
 
1177
try Expr
 
1178
catch
 
1179
    throw:Term -> Term;
 
1180
    exit:Reason -> {'EXIT',Reason}
 
1181
    error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}}
 
1182
end</code>
 
1183
  </section>
 
1184
 
 
1185
  <section>
 
1186
    <title>Parenthesized Expressions</title>
 
1187
    <pre>
 
1188
(Expr)</pre>
 
1189
    <p>Parenthesized expressions are useful to override
 
1190
      <seealso marker="#prec">operator precedences</seealso>,
 
1191
      for example in arithmetic expressions:</p>
 
1192
    <pre>
 
1193
1> <input>1 + 2 * 3.</input>
 
1194
7
 
1195
2> <input>(1 + 2) * 3.</input>
 
1196
9</pre>
 
1197
  </section>
 
1198
 
 
1199
  <section>
 
1200
    <title>Block Expressions</title>
 
1201
    <pre>
 
1202
begin
 
1203
   Expr1,
 
1204
   ...,
 
1205
   ExprN
 
1206
end</pre>
 
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>
 
1210
  </section>
 
1211
 
 
1212
  <section>
 
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>
 
1223
    <pre>
 
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>
 
1229
 
 
1230
       &nbsp;&nbsp;<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>
 
1234
 
 
1235
       &nbsp;&nbsp;<c><![CDATA[BitstringPattern <= BitStringExpr]]></c>.      <br></br>
 
1236
<c>BitStringExpr</c> must be an expression which evaluates to a
 
1237
       bitstring.</item>
 
1238
      <item>A <em>filter</em> is an expression which evaluates to
 
1239
      <c>true</c> or <c>false</c>.</item>
 
1240
    </list>
 
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>
 
1246
    <pre>
 
1247
1> <input>[X*2 || X &lt;- [1,2,3]].</input>
 
1248
[2,4,6]</pre>
 
1249
    <p>More examples can be found in <em>Programming Examples</em>.</p>
 
1250
  
 
1251
 
 
1252
  </section>
 
1253
 
 
1254
<section>
 
1255
    <title>Bit String Comprehensions</title> 
 
1256
   
 
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>
 
1262
    <pre>
 
1263
&lt;&lt; BitString || Qualifier1,...,QualifierN &gt;&gt;</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
      &nbsp;&nbsp;<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>
 
1272
 
 
1273
       &nbsp;&nbsp;<c><![CDATA[BitstringPattern <= BitStringExpr]]></c>.      <br></br>
 
1274
<c>BitStringExpr</c> must be an expression which evaluates to a
 
1275
       bitstring.</item>
 
1276
      <item>A <em>filter</em> is an expression which evaluates to
 
1277
      <c>true</c> or <c>false</c>.</item>
 
1278
    </list>
 
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>
 
1285
    <p></p>
 
1286
    <p>Example:</p>
 
1287
    <pre>
 
1288
1> <input>&lt;&lt; &lt;&lt; (X*2) &gt;&gt; || 
 
1289
&lt;&lt;X&gt;&gt; &lt;= &lt;&lt; 1,2,3 &gt;&gt; &gt;&gt;.</input>
 
1290
&lt;&lt;2,4,6&gt;&gt;</pre>
 
1291
    <p>More examples can be found in <em>Programming Examples</em>.</p>
 
1292
  </section>
 
1293
 
 
1294
  <section>
 
1295
    <marker id="guards"></marker>
 
1296
    <title>Guard Sequences</title>
 
1297
 
 
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
 
1315
       as false,</item>
 
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>
 
1321
    </list>
 
1322
    <table>
 
1323
      <row>
 
1324
        <cell align="left" valign="middle"><c>is_atom/1</c></cell>
 
1325
      </row>
 
1326
      <row>
 
1327
        <cell align="left" valign="middle"><c>is_binary/1</c></cell>
 
1328
      </row>
 
1329
      <row>
 
1330
        <cell align="left" valign="middle"><c>is_bitstring/1</c></cell>
 
1331
      </row>
 
1332
      <row>
 
1333
        <cell align="left" valign="middle"><c>is_boolean/1</c></cell>
 
1334
      </row>
 
1335
      <row>
 
1336
        <cell align="left" valign="middle"><c>is_float/1</c></cell>
 
1337
      </row>
 
1338
      <row>
 
1339
        <cell align="left" valign="middle"><c>is_function/1</c></cell>
 
1340
      </row>
 
1341
      <row>
 
1342
        <cell align="left" valign="middle"><c>is_function/2</c></cell>
 
1343
      </row>
 
1344
      <row>
 
1345
        <cell align="left" valign="middle"><c>is_integer/1</c></cell>
 
1346
      </row>
 
1347
      <row>
 
1348
        <cell align="left" valign="middle"><c>is_list/1</c></cell>
 
1349
      </row>
 
1350
      <row>
 
1351
        <cell align="left" valign="middle"><c>is_number/1</c></cell>
 
1352
      </row>
 
1353
      <row>
 
1354
        <cell align="left" valign="middle"><c>is_pid/1</c></cell>
 
1355
      </row>
 
1356
      <row>
 
1357
        <cell align="left" valign="middle"><c>is_port/1</c></cell>
 
1358
      </row>
 
1359
      <row>
 
1360
        <cell align="left" valign="middle"><c>is_record/2</c></cell>
 
1361
      </row>
 
1362
      <row>
 
1363
        <cell align="left" valign="middle"><c>is_record/3</c></cell>
 
1364
      </row>
 
1365
      <row>
 
1366
        <cell align="left" valign="middle"><c>is_reference/1</c></cell>
 
1367
      </row>
 
1368
      <row>
 
1369
        <cell align="left" valign="middle"><c>is_tuple/1</c></cell>
 
1370
      </row>
 
1371
      <tcaption>Type Test BIFs.</tcaption>
 
1372
    </table>
 
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>
 
1378
    <table>
 
1379
      <row>
 
1380
        <cell align="left" valign="middle"><c>abs(Number)</c></cell>
 
1381
      </row>
 
1382
      <row>
 
1383
        <cell align="left" valign="middle"><c>bit_size(Bitstring)</c></cell>
 
1384
      </row>
 
1385
      <row>
 
1386
        <cell align="left" valign="middle"><c>byte_size(Bitstring)</c></cell>
 
1387
      </row>
 
1388
      <row>
 
1389
        <cell align="left" valign="middle"><c>element(N, Tuple)</c></cell>
 
1390
      </row>
 
1391
      <row>
 
1392
        <cell align="left" valign="middle"><c>float(Term)</c></cell>
 
1393
      </row>
 
1394
      <row>
 
1395
        <cell align="left" valign="middle"><c>hd(List)</c></cell>
 
1396
      </row>
 
1397
      <row>
 
1398
        <cell align="left" valign="middle"><c>length(List)</c></cell>
 
1399
      </row>
 
1400
      <row>
 
1401
        <cell align="left" valign="middle"><c>node()</c></cell>
 
1402
      </row>
 
1403
      <row>
 
1404
        <cell align="left" valign="middle"><c>node(Pid|Ref|Port)</c></cell>
 
1405
      </row>
 
1406
      <row>
 
1407
        <cell align="left" valign="middle"><c>round(Number)</c></cell>
 
1408
      </row>
 
1409
      <row>
 
1410
        <cell align="left" valign="middle"><c>self()</c></cell>
 
1411
      </row>
 
1412
      <row>
 
1413
        <cell align="left" valign="middle"><c>size(Tuple|Bitstring)</c></cell>
 
1414
      </row>
 
1415
      <row>
 
1416
        <cell align="left" valign="middle"><c>tl(List)</c></cell>
 
1417
      </row>
 
1418
      <row>
 
1419
        <cell align="left" valign="middle"><c>trunc(Number)</c></cell>
 
1420
      </row>
 
1421
      <row>
 
1422
        <cell align="left" valign="middle"><c>tuple_size(Tuple)</c></cell>
 
1423
      </row>
 
1424
      <tcaption>Other BIFs Allowed in Guard Expressions.</tcaption>
 
1425
    </table>
 
1426
 
 
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>
 
1432
 
 
1433
  </section>
 
1434
 
 
1435
  <section>
 
1436
    <marker id="prec"></marker>
 
1437
    <title>Operator Precedence</title>
 
1438
    <p>Operator precedence in falling priority:</p>
 
1439
    <table>
 
1440
      <row>
 
1441
        <cell align="left" valign="middle">:</cell>
 
1442
        <cell align="left" valign="middle">&nbsp;</cell>
 
1443
      </row>
 
1444
      <row>
 
1445
        <cell align="left" valign="middle">#</cell>
 
1446
        <cell align="left" valign="middle">&nbsp;</cell>
 
1447
      </row>
 
1448
      <row>
 
1449
        <cell align="left" valign="middle">Unary + - bnot not</cell>
 
1450
        <cell align="left" valign="middle">&nbsp;</cell>
 
1451
      </row>
 
1452
      <row>
 
1453
        <cell align="left" valign="middle">/ * div rem band and</cell>
 
1454
        <cell align="left" valign="middle">Left associative</cell>
 
1455
      </row>
 
1456
      <row>
 
1457
        <cell align="left" valign="middle">+ - bor bxor bsl bsr or xor</cell>
 
1458
        <cell align="left" valign="middle">Left associative</cell>
 
1459
      </row>
 
1460
      <row>
 
1461
        <cell align="left" valign="middle">++ --</cell>
 
1462
        <cell align="left" valign="middle">Right associative</cell>
 
1463
      </row>
 
1464
      <row>
 
1465
        <cell align="left" valign="middle">== /= =&lt; &lt; >= > =:= =/=</cell>
 
1466
        <cell align="left" valign="middle">&nbsp;</cell>
 
1467
      </row>
 
1468
      <row>
 
1469
        <cell align="left" valign="middle">andalso</cell>
 
1470
        <cell align="left" valign="middle">&nbsp;</cell>
 
1471
      </row>
 
1472
      <row>
 
1473
        <cell align="left" valign="middle">orelse</cell>
 
1474
        <cell align="left" valign="middle">&nbsp;</cell>
 
1475
      </row>
 
1476
      <row>
 
1477
        <cell align="left" valign="middle">= !</cell>
 
1478
        <cell align="left" valign="middle">Right associative</cell>
 
1479
      </row>
 
1480
      <row>
 
1481
        <cell align="left" valign="middle">catch</cell>
 
1482
        <cell align="left" valign="middle">&nbsp;</cell>
 
1483
      </row>
 
1484
      <tcaption>Operator Precedence.</tcaption>
 
1485
    </table>
 
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
 
1490
      right:</p>
 
1491
    <pre>
 
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>
 
1496
  </section>
 
1497
</chapter>
 
1498