<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:fn="http://www.w3.org/2005/02/xpath-functions"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../otp_doc.css" type="text/css"> <title>Erlang -- Expressions</title> </head> <body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container"> <script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript"> <!-- function getWinHeight() { var myHeight = 0; if( typeof( window.innerHeight ) == 'number' ) { //Non-IE myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myHeight = document.body.clientHeight; } return myHeight; } function setscrollpos() { var objf=document.getElementById('loadscrollpos'); document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2; } function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, true); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } addEvent(window, 'load', setscrollpos); //--></script><div id="leftnav"><div class="innertube"> <img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Erlang Reference Manual</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p> <br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p> <ul class="flipMenu" imagepath="../js/flipmenu"> <li id="no" title="Introduction" expanded="false">Introduction<ul> <li><a href="introduction.html"> Top of chapter </a></li> <li title="Purpose"><a href="introduction.html#id73748">Purpose</a></li> <li title="Prerequisites"><a href="introduction.html#id66106">Prerequisites</a></li> <li title="Document Conventions"><a href="introduction.html#id67296">Document Conventions</a></li> <li title="Complete List of BIFs"><a href="introduction.html#id68121">Complete List of BIFs</a></li> <li title="Reserved Words"><a href="introduction.html#id60679">Reserved Words</a></li> <li title="Character Set"><a href="introduction.html#id61758">Character Set</a></li> </ul> </li> <li id="no" title="Data Types" expanded="false">Data Types<ul> <li><a href="data_types.html"> Top of chapter </a></li> <li title="Terms"><a href="data_types.html#id63330">Terms</a></li> <li title="Number"><a href="data_types.html#id68697">Number</a></li> <li title="Atom"><a href="data_types.html#id62285">Atom</a></li> <li title="Bit Strings and Binaries"><a href="data_types.html#id68011">Bit Strings and Binaries</a></li> <li title="Reference"><a href="data_types.html#id58120">Reference</a></li> <li title="Fun"><a href="data_types.html#id67499">Fun</a></li> <li title="Port Identifier"><a href="data_types.html#id69290">Port Identifier</a></li> <li title="Pid"><a href="data_types.html#id60853">Pid</a></li> <li title="Tuple"><a href="data_types.html#id73719">Tuple</a></li> <li title="List"><a href="data_types.html#id73198">List</a></li> <li title="String"><a href="data_types.html#id68626">String</a></li> <li title="Record"><a href="data_types.html#id65682">Record</a></li> <li title="Boolean"><a href="data_types.html#id67471">Boolean</a></li> <li title="Escape Sequences"><a href="data_types.html#id73885">Escape Sequences</a></li> <li title="Type Conversions"><a href="data_types.html#id69219">Type Conversions</a></li> </ul> </li> <li id="no" title="Pattern Matching" expanded="false">Pattern Matching<ul> <li><a href="patterns.html"> Top of chapter </a></li> <li title="Pattern Matching"><a href="patterns.html#id68202">Pattern Matching</a></li> </ul> </li> <li id="no" title="Modules" expanded="false">Modules<ul> <li><a href="modules.html"> Top of chapter </a></li> <li title="Module Syntax"><a href="modules.html#id68326">Module Syntax</a></li> <li title="Module Attributes"><a href="modules.html#id68358">Module Attributes</a></li> <li title="Comments"><a href="modules.html#id74337">Comments</a></li> <li title="The module_info/0 and module_info/1 functions"><a href="modules.html#id74350">The module_info/0 and module_info/1 functions</a></li> </ul> </li> <li id="no" title="Functions" expanded="false">Functions<ul> <li><a href="functions.html"> Top of chapter </a></li> <li title="Function Declaration Syntax"><a href="functions.html#id74609">Function Declaration Syntax</a></li> <li title="Function Evaluation"><a href="functions.html#id74724">Function Evaluation</a></li> <li title="Tail recursion"><a href="functions.html#id74875">Tail recursion</a></li> <li title="Built-In Functions, BIFs"><a href="functions.html#id74908">Built-In Functions, BIFs</a></li> </ul> </li> <li id="no" title="Types and Function Specifications" expanded="false">Types and Function Specifications<ul> <li><a href="typespec.html"> Top of chapter </a></li> <li title="Introduction of Types"><a href="typespec.html#id75024">Introduction of Types</a></li> <li title="Types and their Syntax"><a href="typespec.html#id75072">Types and their Syntax</a></li> <li title="Type declarations of user-defined types"><a href="typespec.html#id75688">Type declarations of user-defined types</a></li> <li title="Type information in record declarations"><a href="typespec.html#id75770">Type information in record declarations</a></li> <li title="Specifications for functions"><a href="typespec.html#id75847">Specifications for functions</a></li> </ul> </li> <li id="loadscrollpos" title="Expressions" expanded="true">Expressions<ul> <li><a href="expressions.html"> Top of chapter </a></li> <li title="Expression Evaluation"><a href="expressions.html#id76067">Expression Evaluation</a></li> <li title="Terms"><a href="expressions.html#id76110">Terms</a></li> <li title="Variables"><a href="expressions.html#id76122">Variables</a></li> <li title="Patterns"><a href="expressions.html#id76253">Patterns</a></li> <li title="Match"><a href="expressions.html#id76372">Match</a></li> <li title="Function Calls"><a href="expressions.html#id76431">Function Calls</a></li> <li title="If"><a href="expressions.html#id76631">If</a></li> <li title="Case"><a href="expressions.html#id76696">Case</a></li> <li title="Send"><a href="expressions.html#id76761">Send</a></li> <li title="Receive"><a href="expressions.html#id76844">Receive</a></li> <li title="Term Comparisons"><a href="expressions.html#id77009">Term Comparisons</a></li> <li title="Arithmetic Expressions"><a href="expressions.html#id77270">Arithmetic Expressions</a></li> <li title="Boolean Expressions"><a href="expressions.html#id77776">Boolean Expressions</a></li> <li title="Short-Circuit Expressions"><a href="expressions.html#id77931">Short-Circuit Expressions</a></li> <li title="List Operations"><a href="expressions.html#id78047">List Operations</a></li> <li title="Bit Syntax Expressions"><a href="expressions.html#id78116">Bit Syntax Expressions</a></li> <li title="Fun Expressions"><a href="expressions.html#id78658">Fun Expressions</a></li> <li title="Catch and Throw"><a href="expressions.html#id78840">Catch and Throw</a></li> <li title="Try"><a href="expressions.html#id78986">Try</a></li> <li title="Parenthesized Expressions"><a href="expressions.html#id79344">Parenthesized Expressions</a></li> <li title="Block Expressions"><a href="expressions.html#id79376">Block Expressions</a></li> <li title="List Comprehensions"><a href="expressions.html#id79401">List Comprehensions</a></li> <li title="Bit String Comprehensions"><a href="expressions.html#id79541">Bit String Comprehensions</a></li> <li title="Guard Sequences"><a href="expressions.html#id79673">Guard Sequences</a></li> <li title="Operator Precedence"><a href="expressions.html#id80211">Operator Precedence</a></li> </ul> </li> <li id="no" title="The Preprocessor" expanded="false">The Preprocessor<ul> <li><a href="macros.html"> Top of chapter </a></li> <li title="File Inclusion"><a href="macros.html#id80530">File Inclusion</a></li> <li title="Defining and Using Macros"><a href="macros.html#id80659">Defining and Using Macros</a></li> <li title="Predefined Macros"><a href="macros.html#id80782">Predefined Macros</a></li> <li title="Macros Overloading"><a href="macros.html#id80850">Macros Overloading</a></li> <li title="Flow Control in Macros"><a href="macros.html#id80919">Flow Control in Macros</a></li> <li title="Stringifying Macro Arguments"><a href="macros.html#id81056">Stringifying Macro Arguments</a></li> </ul> </li> <li id="no" title="Records" expanded="false">Records<ul> <li><a href="records.html"> Top of chapter </a></li> <li title="Defining Records"><a href="records.html#id81178">Defining Records</a></li> <li title="Creating Records"><a href="records.html#id81209">Creating Records</a></li> <li title="Accessing Record Fields"><a href="records.html#id81264">Accessing Record Fields</a></li> <li title="Updating Records"><a href="records.html#id81303">Updating Records</a></li> <li title="Records in Guards"><a href="records.html#id81336">Records in Guards</a></li> <li title="Records in Patterns"><a href="records.html#id81368">Records in Patterns</a></li> <li title="Nested records"><a href="records.html#id81395">Nested records</a></li> <li title="Internal Representation of Records"><a href="records.html#id81430">Internal Representation of Records</a></li> </ul> </li> <li id="no" title="Errors and Error Handling" expanded="false">Errors and Error Handling<ul> <li><a href="errors.html"> Top of chapter </a></li> <li title="Terminology"><a href="errors.html#id81550">Terminology</a></li> <li title="Exceptions"><a href="errors.html#id81678">Exceptions</a></li> <li title="Handling of Run-Time Errors in Erlang"><a href="errors.html#id81851">Handling of Run-Time Errors in Erlang</a></li> <li title="Exit Reasons"><a href="errors.html#id81913">Exit Reasons</a></li> </ul> </li> <li id="no" title="Processes" expanded="false">Processes<ul> <li><a href="processes.html"> Top of chapter </a></li> <li title="Processes"><a href="processes.html#id82387">Processes</a></li> <li title="Process Creation"><a href="processes.html#id82400">Process Creation</a></li> <li title="Registered Processes"><a href="processes.html#id82449">Registered Processes</a></li> <li title="Process Termination"><a href="processes.html#id82560">Process Termination</a></li> <li title="Message Sending"><a href="processes.html#id82650">Message Sending</a></li> <li title="Links"><a href="processes.html#id82679">Links</a></li> <li title="Error Handling"><a href="processes.html#id82744">Error Handling</a></li> <li title="Monitors"><a href="processes.html#id82854">Monitors</a></li> <li title="Process Dictionary"><a href="processes.html#id82946">Process Dictionary</a></li> </ul> </li> <li id="no" title="Distributed Erlang" expanded="false">Distributed Erlang<ul> <li><a href="distributed.html"> Top of chapter </a></li> <li title="Distributed Erlang System"><a href="distributed.html#id83013">Distributed Erlang System</a></li> <li title="Nodes"><a href="distributed.html#id83044">Nodes</a></li> <li title="Node Connections"><a href="distributed.html#id83114">Node Connections</a></li> <li title="epmd"><a href="distributed.html#id83164">epmd</a></li> <li title="Hidden Nodes"><a href="distributed.html#id83184">Hidden Nodes</a></li> <li title="C Nodes"><a href="distributed.html#id83230">C Nodes</a></li> <li title="Security"><a href="distributed.html#id83254">Security</a></li> <li title="Distribution BIFs"><a href="distributed.html#id83364">Distribution BIFs</a></li> <li title="Distribution Command Line Flags"><a href="distributed.html#id83662">Distribution Command Line Flags</a></li> <li title="Distribution Modules"><a href="distributed.html#id83799">Distribution Modules</a></li> </ul> </li> <li id="no" title="Compilation and Code Loading" expanded="false">Compilation and Code Loading<ul> <li><a href="code_loading.html"> Top of chapter </a></li> <li title="Compilation"><a href="code_loading.html#id84002">Compilation</a></li> <li title="Code Loading"><a href="code_loading.html#id84112">Code Loading</a></li> <li title="Code Replacement"><a href="code_loading.html#id84159">Code Replacement</a></li> <li title="Running a function when a module is loaded"><a href="code_loading.html#id84234">Running a function when a module is loaded</a></li> </ul> </li> <li id="no" title="Ports and Port Drivers" expanded="false">Ports and Port Drivers<ul> <li><a href="ports.html"> Top of chapter </a></li> <li title="Ports"><a href="ports.html#id84374">Ports</a></li> <li title="Port Drivers"><a href="ports.html#id84409">Port Drivers</a></li> <li title="Port BIFs"><a href="ports.html#id84449">Port BIFs</a></li> </ul> </li> </ul> </div></div> <div id="content"> <div class="innertube"> <h1>7 Expressions</h1> <p>In this chapter, all valid Erlang expressions are listed. When writing Erlang programs, it is also allowed to use macro- and record expressions. However, these expressions are expanded during compilation and are in that sense not true Erlang expressions. Macro- and record expressions are covered in separate chapters: <span class="bold_code"><a href="macros.html">Macros</a></span> and <span class="bold_code"><a href="records.html">Records</a></span>.</p> <h3><a name="id76067">7.1 Expression Evaluation</a></h3> <p>All subexpressions are evaluated before an expression itself is evaluated, unless explicitly stated otherwise. For example, consider the expression:</p> <div class="example"><pre> Expr1 + Expr2</pre></div> <p><span class="code">Expr1</span> and <span class="code">Expr2</span>, which are also expressions, are evaluated first - in any order - before the addition is performed.</p> <p>Many of the operators can only be applied to arguments of a certain type. For example, arithmetic operators can only be applied to numbers. An argument of the wrong type will cause a <span class="code">badarg</span> run-time error.</p> <h3><a name="id76110">7.2 Terms</a></h3> <a name="term"></a> <p>The simplest form of expression is a term, that is an integer, float, atom, string, list or tuple. The return value is the term itself.</p> <h3><a name="id76122">7.3 Variables</a></h3> <p>A variable is an expression. If a variable is bound to a value, the return value is this value. Unbound variables are only allowed in patterns.</p> <p>Variables start with an uppercase letter or underscore (_) and may contain alphanumeric characters, underscore and @. Examples:</p> <div class="example"><pre> X Name1 PhoneNumber Phone_number _ _Height</pre></div> <p>Variables are bound to values using <span class="bold_code"><a href="patterns.html">pattern matching</a></span>. Erlang uses <strong>single assignment</strong>, a variable can only be bound once.</p> <p>The <strong>anonymous variable</strong> is denoted by underscore (_) and can be used when a variable is required but its value can be ignored. Example:</p> <div class="example"><pre> [H|_] = [1,2,3]</pre></div> <p>Variables starting with underscore (_), for example <span class="code">_Height</span>, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they will not generate any warnings for unused variables. Example: The following code</p> <div class="example"><pre> member(_, []) -> [].</pre></div> <p>can be rewritten to be more readable:</p> <div class="example"><pre> member(Elem, []) -> [].</pre></div> <p>This will however cause a warning for an unused variable <span class="code">Elem</span>, if the code is compiled with the flag <span class="code">warn_unused_vars</span> set. Instead, the code can be rewritten to:</p> <div class="example"><pre> member(_Elem, []) -> [].</pre></div> <p>Note that since variables starting with an underscore are not anonymous, this will match:</p> <div class="example"><pre> {_,_} = {1,2}</pre></div> <p>But this will fail:</p> <div class="example"><pre> {_N,_N} = {1,2}</pre></div> <p>The scope for a variable is its function clause. Variables bound in a branch of an <span class="code">if</span>, <span class="code">case</span>, or <span class="code">receive</span> expression must be bound in all branches to have a value outside the expression, otherwise they will be regarded as 'unsafe' outside the expression.</p> <p>For the <span class="code">try</span> expression introduced in Erlang 5.4/OTP-R10B, variable scoping is limited so that variables bound in the expression are always 'unsafe' outside the expression. This will be improved.</p> <h3><a name="id76253">7.4 Patterns</a></h3> <a name="pattern"></a> <p>A pattern has the same structure as a term but may contain unbound variables. Example:</p> <div class="example"><pre> Name1 [H|T] {error,Reason}</pre></div> <p>Patterns are allowed in clause heads, <span class="code">case</span> and <span class="code">receive</span> expressions, and match expressions.</p> <h4>Match Operator = in Patterns</h4> <p>If <span class="code">Pattern1</span> and <span class="code">Pattern2</span> are valid patterns, then the following is also a valid pattern:</p> <div class="example"><pre> Pattern1 = Pattern2</pre></div> <p>When matched against a term, both <span class="code">Pattern1</span> and <span class="code">Pattern2</span> will be matched against the term. The idea behind this feature is to avoid reconstruction of terms. Example:</p> <div class="example"><pre> f({connect,From,To,Number,Options}, To) -> Signal = {connect,From,To,Number,Options}, ...; f(Signal, To) -> ignore.</pre></div> <p>can instead be written as</p> <div class="example"><pre> f({connect,_,To,_,_} = Signal, To) -> ...; f(Signal, To) -> ignore.</pre></div> <h4>String Prefix in Patterns</h4> <p>When matching strings, the following is a valid pattern:</p> <div class="example"><pre> f("prefix" ++ Str) -> ...</pre></div> <p>This is syntactic sugar for the equivalent, but harder to read</p> <div class="example"><pre> f([$p,$r,$e,$f,$i,$x | Str]) -> ...</pre></div> <h4>Expressions in Patterns</h4> <p>An arithmetic expression can be used within a pattern, if it uses only numeric or bitwise operators, and if its value can be evaluated to a constant at compile-time. Example:</p> <div class="example"><pre> case {Value, Result} of {?THRESHOLD+1, ok} -> ...</pre></div> <p>This feature was added in Erlang 5.0/OTP R7.</p> <h3><a name="id76372">7.5 Match</a></h3> <div class="example"><pre> Expr1 = Expr2</pre></div> <p>Matches <span class="code">Expr1</span>, a pattern, against <span class="code">Expr2</span>. If the matching succeeds, any unbound variable in the pattern becomes bound and the value of <span class="code">Expr2</span> is returned.</p> <p>If the matching fails, a <span class="code">badmatch</span> run-time error will occur.</p> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">{A, B} = {answer, 42}.</span> {answer,42} 2> <span class="bold_code">A.</span> answer 3> <span class="bold_code">{C, D} = [1, 2].</span> ** exception error: no match of right hand side value [1,2]</pre></div> <h3><a name="id76431">7.6 Function Calls</a></h3> <a name="calls"></a> <div class="example"><pre> ExprF(Expr1,...,ExprN) ExprM:ExprF(Expr1,...,ExprN)</pre></div> <p>In the first form of function calls, <span class="code">ExprM:ExprF(Expr1,...,ExprN)</span>, each of <span class="code">ExprM</span> and <span class="code">ExprF</span> must be an atom or an expression that evaluates to an atom. The function is said to be called by using the <strong>fully qualified function name</strong>. This is often referred to as a <strong>remote</strong> or <strong>external function call</strong>. Example:</p> <div class="example"><pre> lists:keysearch(Name, 1, List)</pre></div> <p>In the second form of function calls, <span class="code">ExprF(Expr1,...,ExprN)</span>, <span class="code">ExprF</span> must be an atom or evaluate to a fun.</p> <p>If <span class="code">ExprF</span> is an atom the function is said to be called by using the <strong>implicitly qualified function name</strong>. If the function <span class="code">ExprF</span> is locally defined, it is called. Alternatively if <span class="code">ExprF</span> is explicitly imported from module <span class="code">M</span>, <span class="code">M:ExprF(Expr1,...,ExprN)</span> is called. If <span class="code">ExprF</span> is neither declared locally nor explicitly imported, <span class="code">ExprF</span> must be the name of an automatically imported BIF. Examples:</p> <div class="example"><pre> handle(Msg, State) spawn(m, init, [])</pre></div> <p>Examples where ExprF is a fun:</p> <div class="example"><pre> Fun1 = fun(X) -> X+1 end Fun1(3) => 4 Fun2 = {lists,append} Fun2([1,2], [3,4]) => [1,2,3,4] fun lists:append/2([1,2], [3,4]) => [1,2,3,4]</pre></div> <p>Note that when calling a local function, there is a difference between using the implicitly or fully qualified function name, as the latter always refers to the latest version of the module. See <span class="bold_code"><a href="code_loading.html">Compilation and Code Loading</a></span>.</p> <p>See also the chapter about <span class="bold_code"><a href="functions.html#eval">Function Evaluation</a></span>.</p> <h4>Local Function Names Clashing With Auto-imported BIFs</h4> <p>If a local function has the same name as an auto-imported BIF, the semantics is that implicitly qualified function calls are directed to the locally defined function, not to the BIF. To avoid confusion, there is a compiler directive available, <span class="code">-compile({no_auto_import,[F/A]})</span>, that makes a BIF not being auto-imported. In certain situations, such a compile-directive is mandatory.</p> <div class="warning"> <div class="label">Warning</div> <div class="content"><p><p>Before OTP R14A (ERTS version 5.8), an implicitly qualified function call to a function having the same name as an auto-imported BIF always resulted in the BIF being called. In newer versions of the compiler the local function is instead called. The change is there to avoid that future additions to the set of auto-imported BIFs does not silently change the behavior of old code.</p> <p>However, to avoid that old (pre R14) code changed its behavior when compiled with OTP version R14A or later, the following restriction applies: If you override the name of a BIF that was auto-imported in OTP versions prior to R14A (ERTS version 5.8) and have an implicitly qualified call to that function in your code, you either need to explicitly remove the auto-import using a compiler directive, or replace the call with a fully qualified function call, otherwise you will get a compilation error. See example below:</p> </p></div> </div> <div class="example"><pre> -export([length/1,f/1]). -compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported length([]) -> 0; length([H|T]) -> 1 + length(T). %% Calls the local funtion length/1 f(X) when erlang:length(X) > 3 -> %% Calls erlang:length/1, %% which is allowed in guards long.</pre></div> <p>The same logic applies to explicitly imported functions from other modules as to locally defined functions. To both import a function from another module and have the function declared in the module at the same time is not allowed.</p> <div class="example"><pre> -export([f/1]). -compile({no_auto_import,[length/1]}). % erlang:length/1 no longer autoimported -import(mod,[length/1]). f(X) when erlang:length(X) > 33 -> %% Calls erlang:lenght/1, %% which is allowed in guards erlang:length(X); %% Explicit call to erlang:length in body f(X) -> length(X). %% mod:length/1 is called</pre></div> <p>For auto-imported BIFs added to Erlang in release R14A and thereafter, overriding the name with a local function or explicit import is always allowed. However, if the <span class="code">-compile({no_auto_import,[F/A])</span> directive is not used, the compiler will issue a warning whenever the function is called in the module using the implicitly qualified function name.</p> <h3><a name="id76631">7.7 If</a></h3> <div class="example"><pre> if GuardSeq1 -> Body1; ...; GuardSeqN -> BodyN end</pre></div> <p>The branches of an <span class="code">if</span>-expression are scanned sequentially until a guard sequence <span class="code">GuardSeq</span> which evaluates to true is found. Then the corresponding <span class="code">Body</span> (sequence of expressions separated by ',') is evaluated.</p> <p>The return value of <span class="code">Body</span> is the return value of the <span class="code">if</span> expression.</p> <p>If no guard sequence is true, an <span class="code">if_clause</span> run-time error will occur. If necessary, the guard expression <span class="code">true</span> can be used in the last branch, as that guard sequence is always true.</p> <p>Example:</p> <div class="example"><pre> is_greater_than(X, Y) -> if X>Y -> true; true -> % works as an 'else' branch false end</pre></div> <h3><a name="id76696">7.8 Case</a></h3> <a name="case"></a> <div class="example"><pre> case Expr of Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN end</pre></div> <p>The expression <span class="code">Expr</span> is evaluated and the patterns <span class="code">Pattern</span> are sequentially matched against the result. If a match succeeds and the optional guard sequence <span class="code">GuardSeq</span> is true, the corresponding <span class="code">Body</span> is evaluated.</p> <p>The return value of <span class="code">Body</span> is the return value of the <span class="code">case</span> expression.</p> <p>If there is no matching pattern with a true guard sequence, a <span class="code">case_clause</span> run-time error will occur.</p> <p>Example:</p> <div class="example"><pre> is_valid_signal(Signal) -> case Signal of {signal, _What, _From, _To} -> true; {signal, _What, _To} -> true; _Else -> false end.</pre></div> <h3><a name="id76761">7.9 Send</a></h3> <a name="send"></a> <div class="example"><pre> Expr1 ! Expr2</pre></div> <p>Sends the value of <span class="code">Expr2</span> as a message to the process specified by <span class="code">Expr1</span>. The value of <span class="code">Expr2</span> is also the return value of the expression.</p> <p><span class="code">Expr1</span> must evaluate to a pid, a registered name (atom) or a tuple <span class="code">{Name,Node}</span>, where <span class="code">Name</span> is an atom and <span class="code">Node</span> a node name, also an atom.</p> <ul> <li>If <span class="code">Expr1</span> evaluates to a name, but this name is not registered, a <span class="code">badarg</span> run-time error will occur.</li> <li>Sending a message to a pid never fails, even if the pid identifies a non-existing process.</li> <li>Distributed message sending, that is if <span class="code">Expr1</span> evaluates to a tuple <span class="code">{Name,Node}</span> (or a pid located at another node), also never fails.</li> </ul> <h3><a name="id76844">7.10 Receive</a></h3> <a name="receive"></a> <div class="example"><pre> receive Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN end</pre></div> <p>Receives messages sent to the process using the send operator (!). The patterns <span class="code">Pattern</span> are sequentially matched against the first message in time order in the mailbox, then the second, and so on. If a match succeeds and the optional guard sequence <span class="code">GuardSeq</span> is true, the corresponding <span class="code">Body</span> is evaluated. The matching message is consumed, that is removed from the mailbox, while any other messages in the mailbox remain unchanged.</p> <p>The return value of <span class="code">Body</span> is the return value of the <span class="code">receive</span> expression.</p> <p><span class="code">receive</span> never fails. Execution is suspended, possibly indefinitely, until a message arrives that does match one of the patterns and with a true guard sequence. </p> <p>Example:</p> <div class="example"><pre> wait_for_onhook() -> receive onhook -> disconnect(), idle(); {connect, B} -> B ! {busy, self()}, wait_for_onhook() end.</pre></div> <p>It is possible to augment the <span class="code">receive</span> expression with a timeout:</p> <div class="example"><pre> receive Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN after ExprT -> BodyT end</pre></div> <p><span class="code">ExprT</span> should evaluate to an integer. The highest allowed value is 16#ffffffff, that is, the value must fit in 32 bits. <span class="code">receive..after</span> works exactly as <span class="code">receive</span>, except that if no matching message has arrived within <span class="code">ExprT</span> milliseconds, then <span class="code">BodyT</span> is evaluated instead and its return value becomes the return value of the <span class="code">receive..after</span> expression.</p> <p>Example:</p> <div class="example"><pre> wait_for_onhook() -> receive onhook -> disconnect(), idle(); {connect, B} -> B ! {busy, self()}, wait_for_onhook() after 60000 -> disconnect(), error() end.</pre></div> <p>It is legal to use a <span class="code">receive..after</span> expression with no branches:</p> <div class="example"><pre> receive after ExprT -> BodyT end</pre></div> <p>This construction will not consume any messages, only suspend execution in the process for <span class="code">ExprT</span> milliseconds and can be used to implement simple timers.</p> <p>Example:</p> <div class="example"><pre> timer() -> spawn(m, timer, [self()]). timer(Pid) -> receive after 5000 -> Pid ! timeout end.</pre></div> <p>There are two special cases for the timeout value <span class="code">ExprT</span>:</p> <dl> <dt><strong><span class="code">infinity</span></strong></dt> <dd>The process should wait indefinitely for a matching message -- this is the same as not using a timeout. Can be useful for timeout values that are calculated at run-time.</dd> <dt><strong>0</strong></dt> <dd>If there is no matching message in the mailbox, the timeout will occur immediately.</dd> </dl> <h3><a name="id77009">7.11 Term Comparisons</a></h3> <div class="example"><pre> Expr1 <span class="bold_code">op</span> Expr2</pre></div> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle"><strong>op</strong></td> <td align="left" valign="middle"><strong>Description</strong></td> </tr> <tr> <td align="left" valign="middle">==</td> <td align="left" valign="middle">equal to</td> </tr> <tr> <td align="left" valign="middle">/=</td> <td align="left" valign="middle">not equal to</td> </tr> <tr> <td align="left" valign="middle">=<</td> <td align="left" valign="middle">less than or equal to</td> </tr> <tr> <td align="left" valign="middle"><</td> <td align="left" valign="middle">less than</td> </tr> <tr> <td align="left" valign="middle">>=</td> <td align="left" valign="middle">greater than or equal to</td> </tr> <tr> <td align="left" valign="middle">></td> <td align="left" valign="middle">greater than</td> </tr> <tr> <td align="left" valign="middle">=:=</td> <td align="left" valign="middle">exactly equal to</td> </tr> <tr> <td align="left" valign="middle">=/=</td> <td align="left" valign="middle">exactly not equal to</td> </tr> </table> <em>Table 7.1: Term Comparison Operators.</em> <p>The arguments may be of different data types. The following order is defined:</p> <div class="example"><pre> number < atom < reference < fun < port < pid < tuple < list < bit string</pre></div> <p>Lists are compared element by element. Tuples are ordered by size, two tuples with the same size are compared element by element.</p> <p>When comparing an integer to a float, the term with the lesser precision will be converted into the other term's type, unless the operator is one of =:= or =/=. A float is more precise than an integer until all significant figures of the float are to the left of the decimal point. This happens when the float is larger/smaller than +/-9007199254740992.0. The conversion strategy is changed depending on the size of the float because otherwise comparison of large floats and integers would lose their transitivity.</p> <p>Returns the Boolean value of the expression, <span class="code">true</span> or <span class="code">false</span>.</p> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">1==1.0.</span> true 2> <span class="bold_code">1=:=1.0.</span> false 3> <span class="bold_code">1 > a.</span> false</pre></div> <h3><a name="id77270">7.12 Arithmetic Expressions</a></h3> <div class="example"><pre> <span class="bold_code">op</span> Expr Expr1 <span class="bold_code">op</span> Expr2</pre></div> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle"><strong>op</strong></td> <td align="left" valign="middle"><strong>Description</strong></td> <td align="left" valign="middle"><strong>Argument type</strong></td> </tr> <tr> <td align="left" valign="middle">+</td> <td align="left" valign="middle">unary +</td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">-</td> <td align="left" valign="middle">unary -</td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">+</td> <td align="left" valign="middle"> </td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">-</td> <td align="left" valign="middle"> </td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">*</td> <td align="left" valign="middle"> </td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">/</td> <td align="left" valign="middle">floating point division</td> <td align="left" valign="middle">number</td> </tr> <tr> <td align="left" valign="middle">bnot</td> <td align="left" valign="middle">unary bitwise not</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">div</td> <td align="left" valign="middle">integer division</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">rem</td> <td align="left" valign="middle">integer remainder of X/Y</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">band</td> <td align="left" valign="middle">bitwise and</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">bor</td> <td align="left" valign="middle">bitwise or</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">bxor</td> <td align="left" valign="middle">arithmetic bitwise xor</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">bsl</td> <td align="left" valign="middle">arithmetic bitshift left</td> <td align="left" valign="middle">integer</td> </tr> <tr> <td align="left" valign="middle">bsr</td> <td align="left" valign="middle">bitshift right</td> <td align="left" valign="middle">integer</td> </tr> </table> <em>Table 7.2: Arithmetic Operators.</em> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">+1.</span> 1 2> <span class="bold_code">-1.</span> -1 3> <span class="bold_code">1+1.</span> 2 4> <span class="bold_code">4/2.</span> 2.0 5> <span class="bold_code">5 div 2.</span> 2 6> <span class="bold_code">5 rem 2.</span> 1 7> <span class="bold_code">2#10 band 2#01.</span> 0 8> <span class="bold_code">2#10 bor 2#01.</span> 3 9> <span class="bold_code">a + 10.</span> ** exception error: an error occurred when evaluating an arithmetic expression in operator +/2 called as a + 10 10> <span class="bold_code">1 bsl (1 bsl 64).</span> ** exception error: a system limit has been reached in operator bsl/2 called as 1 bsl 18446744073709551616</pre></div> <h3><a name="id77776">7.13 Boolean Expressions</a></h3> <div class="example"><pre> <span class="bold_code">op</span> Expr Expr1 <span class="bold_code">op</span> Expr2</pre></div> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle"><strong>op</strong></td> <td align="left" valign="middle"><strong>Description</strong></td> </tr> <tr> <td align="left" valign="middle">not</td> <td align="left" valign="middle">unary logical not</td> </tr> <tr> <td align="left" valign="middle">and</td> <td align="left" valign="middle">logical and</td> </tr> <tr> <td align="left" valign="middle">or</td> <td align="left" valign="middle">logical or</td> </tr> <tr> <td align="left" valign="middle">xor</td> <td align="left" valign="middle">logical xor</td> </tr> </table> <em>Table 7.3: Logical Operators.</em> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">not true.</span> false 2> <span class="bold_code">true and false.</span> false 3> <span class="bold_code">true xor false.</span> true 4> <span class="bold_code">true or garbage.</span> ** exception error: bad argument in operator or/2 called as true or garbage</pre></div> <h3><a name="id77931">7.14 Short-Circuit Expressions</a></h3> <div class="example"><pre> Expr1 orelse Expr2 Expr1 andalso Expr2</pre></div> <p>Expressions where <span class="code">Expr2</span> is evaluated only if necessary. That is, <span class="code">Expr2</span> is evaluated only if <span class="code">Expr1</span> evaluates to <span class="code">false</span> in an <span class="code">orelse</span> expression, or only if <span class="code">Expr1</span> evaluates to <span class="code">true</span> in an <span class="code">andalso</span> expression. Returns either the value of <span class="code">Expr1</span> (that is, <span class="code">true</span> or <span class="code">false</span>) or the value of <span class="code">Expr2</span> (if <span class="code">Expr2</span> was evaluated).</p> <p>Example 1:</p> <div class="example"><pre> case A >= -1.0 andalso math:sqrt(A+1) > B of</pre></div> <p>This will work even if <span class="code">A</span> is less than <span class="code">-1.0</span>, since in that case, <span class="code">math:sqrt/1</span> is never evaluated.</p> <p>Example 2:</p> <div class="example"><pre> OnlyOne = is_atom(L) orelse (is_list(L) andalso length(L) == 1),</pre></div> <p>From R13A, <span class="code">Expr2</span> is no longer required to evaluate to a boolean value. As a consequence, <span class="code">andalso</span> and <span class="code">orelse</span> are now tail-recursive. For instance, the following function is tail-recursive in R13A and later:</p> <div class="example"><pre> all(Pred, [Hd|Tail]) -> Pred(Hd) andalso all(Pred, Tail); all(_, []) -> true.</pre></div> <h3><a name="id78047">7.15 List Operations</a></h3> <div class="example"><pre> Expr1 ++ Expr2 Expr1 -- Expr2</pre></div> <p>The list concatenation operator <span class="code">++</span> appends its second argument to its first and returns the resulting list.</p> <p>The list subtraction operator <span class="code">--</span> produces a list which is a copy of the first argument, subjected to the following procedure: for each element in the second argument, the first occurrence of this element (if any) is removed.</p> <p>Example:</p> <div class="example"><pre> 1> <span class="bold_code">[1,2,3]++[4,5].</span> [1,2,3,4,5] 2> <span class="bold_code">[1,2,3,2,1,2]--[2,1,2].</span> [3,1,2]</pre></div> <div class="warning"> <div class="label">Warning</div> <div class="content"><p><p>The complexity of <span class="code">A -- B</span> is proportional to <span class="code">length(A)*length(B)</span>, meaning that it will be very slow if both <span class="code">A</span> and <span class="code">B</span> are long lists.</p></p></div> </div> <h3><a name="id78116">7.16 Bit Syntax Expressions</a></h3> <a name="bit_syntax"></a> <div class="example"><pre><<>> <<E1,...,En>></pre></div> <p>Each element <span class="code">Ei</span> specifies a <strong>segment</strong> of the bit string. Each element <span class="code">Ei</span> is a value, followed by an optional <strong>size expression</strong> and an optional <strong>type specifier list</strong>.</p> <div class="example"><pre> Ei = Value | Value:Size | Value/TypeSpecifierList | Value:Size/TypeSpecifierList</pre></div> <p>Used in a bit string construction, <span class="code">Value</span> is an expression which should evaluate to an integer, float or bit string. If the expression is something else than a single literal or variable, it should be enclosed in parenthesis.</p> <p>Used in a bit string matching, <span class="code">Value</span> must be a variable, or an integer, float or string.</p> <p>Note that, for example, using a string literal as in <span class="code"><<"abc">></span> is syntactic sugar for <span class="code"><<$a,$b,$c>></span>.</p> <p>Used in a bit string construction, <span class="code">Size</span> is an expression which should evaluate to an integer.</p> <p>Used in a bit string matching, <span class="code">Size</span> must be an integer or a variable bound to an integer.</p> <p>The value of <span class="code">Size</span> specifies the size of the segment in units (see below). The default value depends on the type (see below). For <span class="code">integer</span> it is 8, for <span class="code">float</span> it is 64, for <span class="code">binary</span> and <span class="code">bitstring</span> it is the whole binary or bit string. In matching, this default value is only valid for the very last element. All other bit string or binary elements in the matching must have a size specification.</p> <p>For the <span class="code">utf8</span>, <span class="code">utf16</span>, and <span class="code">utf32</span> types, <span class="code">Size</span> must not be given. The size of the segment is implicitly determined by the type and value itself.</p> <p><span class="code">TypeSpecifierList</span> is a list of type specifiers, in any order, separated by hyphens (-). Default values are used for any omitted type specifiers.</p> <dl> <dt><strong><span class="code">Type</span>= <span class="code">integer</span> | <span class="code">float</span> | <span class="code">binary</span> | <span class="code">bytes</span> | <span class="code">bitstring</span> | <span class="code">bits</span> | <span class="code">utf8</span> | <span class="code">utf16</span> | <span class="code">utf32</span> </strong></dt> <dd>The default is <span class="code">integer</span>. <span class="code">bytes</span> is a shorthand for <span class="code">binary</span> and <span class="code">bits</span> is a shorthand for <span class="code">bitstring</span>. See below for more information about the <span class="code">utf</span> types. </dd> <dt><strong><span class="code">Signedness</span>= <span class="code">signed</span> | <span class="code">unsigned</span></strong></dt> <dd>Only matters for matching and when the type is <span class="code">integer</span>. The default is <span class="code">unsigned</span>.</dd> <dt><strong><span class="code">Endianness</span>= <span class="code">big</span> | <span class="code">little</span> | <span class="code">native</span></strong></dt> <dd>Native-endian means that the endianness will be resolved at load time to be either big-endian or little-endian, depending on what is native for the CPU that the Erlang machine is run on. Endianness only matters when the Type is either <span class="code">integer</span>, <span class="code">utf16</span>, <span class="code">utf32</span>, or <span class="code">float</span>. The default is <span class="code">big</span>. </dd> <dt><strong><span class="code">Unit</span>= <span class="code">unit:IntegerLiteral</span></strong></dt> <dd>The allowed range is 1..256. Defaults to 1 for <span class="code">integer</span>, <span class="code">float</span> and <span class="code">bitstring</span>, and to 8 for <span class="code">binary</span>. No unit specifier must be given for the types <span class="code">utf8</span>, <span class="code">utf16</span>, and <span class="code">utf32</span>. </dd> </dl> <p>The value of <span class="code">Size</span> multiplied with the unit gives the number of bits. A segment of type <span class="code">binary</span> must have a size that is evenly divisible by 8.</p> <div class="note"> <div class="label">Note</div> <div class="content"><p><p>When constructing binaries, if the size <span class="code">N</span> of an integer segment is too small to contain the given integer, the most significant bits of the integer will be silently discarded and only the <span class="code">N</span> least significant bits will be put into the binary.</p></p></div> </div> <p>The types <span class="code">utf8</span>, <span class="code">utf16</span>, and <span class="code">utf32</span> specifies encoding/decoding of the <strong>Unicode Transformation Format</strong>s UTF-8, UTF-16, and UTF-32, respectively.</p> <p>When constructing a segment of a <span class="code">utf</span> type, <span class="code">Value</span> must be an integer in the range 0..16#D7FF or 16#E000....16#10FFFF. Construction will fail with a <span class="code">badarg</span> exception if <span class="code">Value</span> is outside the allowed ranges. The size of the resulting binary segment depends on the type and/or <span class="code">Value</span>. For <span class="code">utf8</span>, <span class="code">Value</span> will be encoded in 1 through 4 bytes. For <span class="code">utf16</span>, <span class="code">Value</span> will be encoded in 2 or 4 bytes. Finally, for <span class="code">utf32</span>, <span class="code">Value</span> will always be encoded in 4 bytes.</p> <p>When constructing, a literal string may be given followed by one of the UTF types, for example: <span class="code"><<"abc"/utf8>></span> which is syntatic sugar for <span class="code"><<$a/utf8,$b/utf8,$c/utf8>></span>.</p> <p>A successful match of a segment of a <span class="code">utf</span> type results in an integer in the range 0..16#D7FF or 16#E000..16#10FFFF. The match will fail if returned value would fall outside those ranges.</p> <p>A segment of type <span class="code">utf8</span> will match 1 to 4 bytes in the binary, if the binary at the match position contains a valid UTF-8 sequence. (See RFC-3629 or the Unicode standard.)</p> <p>A segment of type <span class="code">utf16</span> may match 2 or 4 bytes in the binary. The match will fail if the binary at the match position does not contain a legal UTF-16 encoding of a Unicode code point. (See RFC-2781 or the Unicode standard.)</p> <p>A segment of type <span class="code">utf32</span> may match 4 bytes in the binary in the same way as an <span class="code">integer</span> segment matching 32 bits. The match will fail if the resulting integer is outside the legal ranges mentioned above.</p> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">Bin1 = <<1,17,42>>.</span> <<1,17,42>> 2> <span class="bold_code">Bin2 = <<"abc">>.</span> <<97,98,99>> 3> <span class="bold_code">Bin3 = <<1,17,42:16>>.</span> <<1,17,0,42>> 4> <span class="bold_code"><<A,B,C:16>> = <<1,17,42:16>>.</span> <<1,17,0,42>> 5> <span class="bold_code">C.</span> 42 6> <span class="bold_code"><<D:16,E,F>> = <<1,17,42:16>>.</span> <<1,17,0,42>> 7> <span class="bold_code">D.</span> 273 8> <span class="bold_code">F.</span> 42 9> <span class="bold_code"><<G,H/binary>> = <<1,17,42:16>>.</span> <<1,17,0,42>> 10> <span class="bold_code">H.</span> <<17,0,42>> 11> <span class="bold_code"><<G,H/bitstring>> = <<1,17,42:12>>.</span> <<1,17,1,10:4>> 12> <span class="bold_code">H.</span> <<17,1,10:4>> 13> <span class="bold_code"><<1024/utf8>>.</span> <<208,128>> </pre></div> <p>Note that bit string patterns cannot be nested.</p> <p>Note also that "<span class="code">B=<<1>></span>" is interpreted as "<span class="code">B =<<1>></span>" which is a syntax error. The correct way is to write a space after '=': "<span class="code">B= <<1>></span>.</p> <p>More examples can be found in <strong>Programming Examples</strong>.</p> <h3><a name="id78658">7.17 Fun Expressions</a></h3> <a name="funs"></a> <div class="example"><pre> fun (Pattern11,...,Pattern1N) [when GuardSeq1] -> Body1; ...; (PatternK1,...,PatternKN) [when GuardSeqK] -> BodyK end</pre></div> <p>A fun expression begins with the keyword <span class="code">fun</span> and ends with the keyword <span class="code">end</span>. Between them should be a function declaration, similar to a <span class="bold_code"><a href="functions.html#syntax">regular function declaration</a></span>, except that no function name is specified.</p> <p>Variables in a fun head shadow variables in the function clause surrounding the fun expression, and variables bound in a fun body are local to the fun body.</p> <p>The return value of the expression is the resulting fun.</p> <p>Examples:</p> <div class="example"><pre> 1> <span class="bold_code">Fun1 = fun (X) -> X+1 end.</span> #Fun<erl_eval.6.39074546> 2> <span class="bold_code">Fun1(2).</span> 3 3> <span class="bold_code">Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.</span> #Fun<erl_eval.6.39074546> 4> <span class="bold_code">Fun2(7).</span> gt</pre></div> <p>The following fun expressions are also allowed:</p> <div class="example"><pre> fun Name/Arity fun Module:Name/Arity</pre></div> <p>In <span class="code">Name/Arity</span>, <span class="code">Name</span> is an atom and <span class="code">Arity</span> is an integer. <span class="code">Name/Arity</span> must specify an existing local function. The expression is syntactic sugar for:</p> <div class="example"><pre> fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end</pre></div> <p>In <span class="code">Module:Name/Arity</span>, <span class="code">Module</span> and <span class="code">Name</span> are atoms and <span class="code">Arity</span> is an integer. Starting from the R15 release, <span class="code">Module</span>, <span class="code">Name</span>, and <span class="code">Arity</span> may also be variables. A fun defined in this way will refer to the function <span class="code">Name</span> with arity <span class="code">Arity</span> in the <strong>latest</strong> version of module <span class="code">Module</span>. A fun defined in this way will not be dependent on the code for module in which it is defined. </p> <p>When applied to a number N of arguments, a tuple <span class="code">{Module,FunctionName}</span> is interpreted as a fun, referring to the function <span class="code">FunctionName</span> with arity N in the module <span class="code">Module</span>. The function must be exported. <strong>This usage is deprecated.</strong> Use <span class="code">fun Module:Name/Arity</span> instead. See <span class="bold_code"><a href="#calls">Function Calls</a></span> for an example.</p> <p>More examples can be found in <strong>Programming Examples</strong>.</p> <h3><a name="id78840">7.18 Catch and Throw</a></h3> <a name="catch"></a> <div class="example"><pre> catch Expr</pre></div> <p>Returns the value of <span class="code">Expr</span> unless an exception occurs during the evaluation. In that case, the exception is caught. For exceptions of class <span class="code">error</span>, that is run-time errors: <span class="code">{'EXIT',{Reason,Stack}}</span> is returned. For exceptions of class <span class="code">exit</span>, that is the code called <span class="code">exit(Term)</span>: <span class="code">{'EXIT',Term}</span> is returned. For exceptions of class <span class="code">throw</span>, that is the code called <span class="code">throw(Term)</span>: <span class="code">Term</span> is returned.</p> <p><span class="code">Reason</span> depends on the type of error that occurred, and <span class="code">Stack</span> is the stack of recent function calls, see <span class="bold_code"><a href="errors.html#exit_reasons">Errors and Error Handling</a></span>.</p> <p>Examples:</p> <p></p> <div class="example"><pre> 1> <span class="bold_code">catch 1+2.</span> 3 2> <span class="bold_code">catch 1+a.</span> {'EXIT',{badarith,[...]}}</pre></div> <p>Note that <span class="code">catch</span> has low precedence and catch subexpressions often needs to be enclosed in a block expression or in parenthesis:</p> <div class="example"><pre> 3> <span class="bold_code">A = catch 1+2.</span> ** 1: syntax error before: 'catch' ** 4> <span class="bold_code">A = (catch 1+2).</span> 3</pre></div> <p>The BIF <span class="code">throw(Any)</span> can be used for non-local return from a function. It must be evaluated within a <span class="code">catch</span>, which will return the value <span class="code">Any</span>. Example:</p> <div class="example"><pre> 5> <span class="bold_code">catch throw(hello).</span> hello</pre></div> <p>If <span class="code">throw/1</span> is not evaluated within a catch, a <span class="code">nocatch</span> run-time error will occur.</p> <h3><a name="id78986">7.19 Try</a></h3> <a name="try"></a> <div class="example"><pre> try Exprs catch [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> ExceptionBody1; [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] -> ExceptionBodyN end</pre></div> <p>This is an enhancement of <span class="bold_code"><a href="#catch">catch</a></span> that appeared in Erlang 5.4/OTP-R10B. It gives the possibility do distinguish between different exception classes, and to choose to handle only the desired ones, passing the others on to an enclosing <span class="code">try</span> or <span class="code">catch</span> or to default error handling.</p> <p>Note that although the keyword <span class="code">catch</span> is used in the <span class="code">try</span> expression, there is not a <span class="code">catch</span> expression within the <span class="code">try</span> expression.</p> <p>Returns the value of <span class="code">Exprs</span> (a sequence of expressions <span class="code">Expr1, ..., ExprN</span>) unless an exception occurs during the evaluation. In that case the exception is caught and the patterns <span class="code">ExceptionPattern</span> with the right exception class <span class="code">Class</span> are sequentially matched against the caught exception. An omitted <span class="code">Class</span> is shorthand for <span class="code">throw</span>. If a match succeeds and the optional guard sequence <span class="code">ExceptionGuardSeq</span> is true, the corresponding <span class="code">ExceptionBody</span> is evaluated to become the return value.</p> <p>If an exception occurs during evaluation of <span class="code">Exprs</span> but there is no matching <span class="code">ExceptionPattern</span> of the right <span class="code">Class</span> with a true guard sequence, the exception is passed on as if <span class="code">Exprs</span> had not been enclosed in a <span class="code">try</span> expression.</p> <p>If an exception occurs during evaluation of <span class="code">ExceptionBody</span> it is not caught.</p> <p>The <span class="code">try</span> expression can have an <span class="code">of</span> section: </p> <div class="example"><pre> try Exprs of Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN catch [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> ExceptionBody1; ...; [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] -> ExceptionBodyN end</pre></div> <p>If the evaluation of <span class="code">Exprs</span> succeeds without an exception, the patterns <span class="code">Pattern</span> are sequentially matched against the result in the same way as for a <span class="bold_code"><a href="#case">case</a></span> expression, except that if the matching fails, a <span class="code">try_clause</span> run-time error will occur.</p> <p>An exception occurring during the evaluation of <span class="code">Body</span> is not caught.</p> <p>The <span class="code">try</span> expression can also be augmented with an <span class="code">after</span> section, intended to be used for cleanup with side effects:</p> <div class="example"><pre> try Exprs of Pattern1 [when GuardSeq1] -> Body1; ...; PatternN [when GuardSeqN] -> BodyN catch [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> ExceptionBody1; ...; [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] -> ExceptionBodyN after AfterBody end</pre></div> <p><span class="code">AfterBody</span> is evaluated after either <span class="code">Body</span> or <span class="code">ExceptionBody</span> no matter which one. The evaluated value of <span class="code">AfterBody</span> is lost; the return value of the <span class="code">try</span> expression is the same with an <span class="code">after</span> section as without.</p> <p>Even if an exception occurs during evaluation of <span class="code">Body</span> or <span class="code">ExceptionBody</span>, <span class="code">AfterBody</span> is evaluated. In this case the exception is passed on after <span class="code">AfterBody</span> has been evaluated, so the exception from the <span class="code">try</span> expression is the same with an <span class="code">after</span> section as without.</p> <p>If an exception occurs during evaluation of <span class="code">AfterBody</span> itself it is not caught, so if <span class="code">AfterBody</span> is evaluated after an exception in <span class="code">Exprs</span>, <span class="code">Body</span> or <span class="code">ExceptionBody</span>, that exception is lost and masked by the exception in <span class="code">AfterBody</span>.</p> <p>The <span class="code">of</span>, <span class="code">catch</span> and <span class="code">after</span> sections are all optional, as long as there is at least a <span class="code">catch</span> or an <span class="code">after</span> section, so the following are valid <span class="code">try</span> expressions:</p> <div class="example"><pre> try Exprs of Pattern when GuardSeq -> Body after AfterBody end try Exprs catch ExpressionPattern -> ExpressionBody after AfterBody end try Exprs after AfterBody end</pre></div> <p>Example of using <span class="code">after</span>, this code will close the file even in the event of exceptions in <span class="code">file:read/2</span> or in <span class="code">binary_to_term/1</span>, and exceptions will be the same as without the <span class="code">try</span>...<span class="code">after</span>...<span class="code">end</span> expression:</p> <div class="example"><pre> termize_file(Name) -> {ok,F} = file:open(Name, [read,binary]), try {ok,Bin} = file:read(F, 1024*1024), binary_to_term(Bin) after file:close(F) end.</pre></div> <p>Example: Using <span class="code">try</span> to emulate <span class="code">catch Expr</span>.</p> <div class="example"><pre> try Expr catch throw:Term -> Term; exit:Reason -> {'EXIT',Reason} error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}} end</pre></div> <h3><a name="id79344">7.20 Parenthesized Expressions</a></h3> <div class="example"><pre> (Expr)</pre></div> <p>Parenthesized expressions are useful to override <span class="bold_code"><a href="#prec">operator precedences</a></span>, for example in arithmetic expressions:</p> <div class="example"><pre> 1> <span class="bold_code">1 + 2 * 3.</span> 7 2> <span class="bold_code">(1 + 2) * 3.</span> 9</pre></div> <h3><a name="id79376">7.21 Block Expressions</a></h3> <div class="example"><pre> begin Expr1, ..., ExprN end</pre></div> <p>Block expressions provide a way to group a sequence of expressions, similar to a clause body. The return value is the value of the last expression <span class="code">ExprN</span>.</p> <h3><a name="id79401">7.22 List Comprehensions</a></h3> <a name="lcs"></a> <p>List comprehensions are a feature of many modern functional programming languages. Subject to certain rules, they provide a succinct notation for generating elements in a list.</p> <p>List comprehensions are analogous to set comprehensions in Zermelo-Frankel set theory and are called ZF expressions in Miranda. They are analogous to the <span class="code">setof</span> and <span class="code">findall</span> predicates in Prolog.</p> <p>List comprehensions are written with the following syntax:</p> <div class="example"><pre> [Expr || Qualifier1,...,QualifierN]</pre></div> <p><span class="code">Expr</span> is an arbitrary expression, and each <span class="code">Qualifier</span> is either a generator or a filter.</p> <ul> <li>A <strong>generator</strong> is written as: <br> <span class="code">Pattern <- ListExpr</span>. <br> <span class="code">ListExpr</span> must be an expression which evaluates to a list of terms.</li> <li>A <strong>bit string generator</strong> is written as: <br> <span class="code">BitstringPattern <= BitStringExpr</span>. <br> <span class="code">BitStringExpr</span> must be an expression which evaluates to a bitstring.</li> <li>A <strong>filter</strong> is an expression which evaluates to <span class="code">true</span> or <span class="code">false</span>.</li> </ul> <p>The variables in the generator patterns shadow variables in the function clause surrounding the list comprehensions.</p> <p>A list comprehension returns a list, where the elements are the result of evaluating <span class="code">Expr</span> for each combination of generator list elements and bit string generator elements for which all filters are true.</p> <p></p> <p>Example:</p> <div class="example"><pre> 1> <span class="bold_code">[X*2 || X <- [1,2,3]].</span> [2,4,6]</pre></div> <p>More examples can be found in <strong>Programming Examples</strong>.</p> <h3><a name="id79541">7.23 Bit String Comprehensions</a></h3> <p>Bit string comprehensions are analogous to List Comprehensions. They are used to generate bit strings efficiently and succinctly.</p> <p>Bit string comprehensions are written with the following syntax:</p> <div class="example"><pre> << BitString || Qualifier1,...,QualifierN >></pre></div> <p><span class="code">BitString</span> is a bit string expression, and each <span class="code">Qualifier</span> is either a generator, a bit string generator or a filter.</p> <ul> <li>A <strong>generator</strong> is written as: <br> <span class="code">Pattern <- ListExpr</span>. <br> <span class="code">ListExpr</span> must be an expression which evaluates to a list of terms.</li> <li>A <strong>bit string generator</strong> is written as: <br> <span class="code">BitstringPattern <= BitStringExpr</span>. <br> <span class="code">BitStringExpr</span> must be an expression which evaluates to a bitstring.</li> <li>A <strong>filter</strong> is an expression which evaluates to <span class="code">true</span> or <span class="code">false</span>.</li> </ul> <p>The variables in the generator patterns shadow variables in the function clause surrounding the bit string comprehensions.</p> <p>A bit string comprehension returns a bit string, which is created by concatenating the results of evaluating <span class="code">BitString</span> for each combination of bit string generator elements for which all filters are true.</p> <p></p> <p>Example:</p> <div class="example"><pre> 1> <span class="bold_code"><< << (X*2) >> || <<X>> <= << 1,2,3 >> >>.</span> <<2,4,6>></pre></div> <p>More examples can be found in <strong>Programming Examples</strong>.</p> <h3><a name="id79673">7.24 Guard Sequences</a></h3> <a name="guards"></a> <p>A <strong>guard sequence</strong> is a sequence of guards, separated by semicolon (;). The guard sequence is true if at least one of the guards is true. (The remaining guards, if any, will not be evaluated.)<br> <span class="code">Guard1;...;GuardK</span></p> <p>A <strong>guard</strong> is a sequence of guard expressions, separated by comma (,). The guard is true if all guard expressions evaluate to <span class="code">true</span>.<br> <span class="code">GuardExpr1,...,GuardExprN</span></p> <p>The set of valid <strong>guard expressions</strong> (sometimes called guard tests) is a subset of the set of valid Erlang expressions. The reason for restricting the set of valid expressions is that evaluation of a guard expression must be guaranteed to be free of side effects. Valid guard expressions are:</p> <ul> <li>the atom <span class="code">true</span>,</li> <li>other constants (terms and bound variables), all regarded as false,</li> <li>calls to the BIFs specified below,</li> <li>term comparisons,</li> <li>arithmetic expressions,</li> <li>boolean expressions, and</li> <li>short-circuit expressions (<span class="code">andalso</span>/<span class="code">orelse</span>).</li> </ul> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle"><span class="code">is_atom/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_binary/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_bitstring/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_boolean/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_float/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_function/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_function/2</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_integer/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_list/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_number/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_pid/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_port/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_record/2</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_record/3</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_reference/1</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">is_tuple/1</span></td> </tr> </table> <em>Table 7.4: Type Test BIFs.</em> <p>Note that most type test BIFs have older equivalents, without the <span class="code">is_</span> prefix. These old BIFs are retained for backwards compatibility only and should not be used in new code. They are also only allowed at top level. For example, they are not allowed in boolean expressions in guards.</p> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle"><span class="code">abs(Number)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">bit_size(Bitstring)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">byte_size(Bitstring)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">element(N, Tuple)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">float(Term)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">hd(List)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">length(List)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">node()</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">node(Pid|Ref|Port)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">round(Number)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">self()</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">size(Tuple|Bitstring)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">tl(List)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">trunc(Number)</span></td> </tr> <tr> <td align="left" valign="middle"><span class="code">tuple_size(Tuple)</span></td> </tr> </table> <em>Table 7.5: Other BIFs Allowed in Guard Expressions.</em> <p>If an arithmetic expression, a boolean expression, a short-circuit expression, or a call to a guard BIF fails (because of invalid arguments), the entire guard fails. If the guard was part of a guard sequence, the next guard in the sequence (that is, the guard following the next semicolon) will be evaluated.</p> <h3><a name="id80211">7.25 Operator Precedence</a></h3> <a name="prec"></a> <p>Operator precedence in falling priority:</p> <table border="1" cellpadding="2" cellspacing="0"> <tr> <td align="left" valign="middle">:</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">#</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">Unary + - bnot not</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">/ * div rem band and</td> <td align="left" valign="middle">Left associative</td> </tr> <tr> <td align="left" valign="middle">+ - bor bxor bsl bsr or xor</td> <td align="left" valign="middle">Left associative</td> </tr> <tr> <td align="left" valign="middle">++ --</td> <td align="left" valign="middle">Right associative</td> </tr> <tr> <td align="left" valign="middle">== /= =< < >= > =:= =/=</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">andalso</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">orelse</td> <td align="left" valign="middle"> </td> </tr> <tr> <td align="left" valign="middle">= !</td> <td align="left" valign="middle">Right associative</td> </tr> <tr> <td align="left" valign="middle">catch</td> <td align="left" valign="middle"> </td> </tr> </table> <em>Table 7.6: Operator Precedence.</em> <p>When evaluating an expression, the operator with the highest priority is evaluated first. Operators with the same priority are evaluated according to their associativity. Example: The left associative arithmetic operators are evaluated left to right:</p> <div class="example"><pre> <span class="bold_code">6 + 5 * 4 - 3 / 2</span> evaluates to <span class="bold_code">6 + 20 - 1.5</span> evaluates to <span class="bold_code">26 - 1.5</span> evaluates to <span class="bold_code">24.5</span></pre></div> </div> <div class="footer"> <hr> <p>Copyright © 2003-2012 Ericsson AB. All Rights Reserved.</p> </div> </div> </div></body> </html>