diff options
author | Erlang/OTP <[email protected]> | 2009-11-20 14:54:40 +0000 |
---|---|---|
committer | Erlang/OTP <[email protected]> | 2009-11-20 14:54:40 +0000 |
commit | 84adefa331c4159d432d22840663c38f155cd4c1 (patch) | |
tree | bff9a9c66adda4df2106dfd0e5c053ab182a12bd /system/doc/reference_manual | |
download | otp-84adefa331c4159d432d22840663c38f155cd4c1.tar.gz otp-84adefa331c4159d432d22840663c38f155cd4c1.tar.bz2 otp-84adefa331c4159d432d22840663c38f155cd4c1.zip |
The R13B03 release.OTP_R13B03
Diffstat (limited to 'system/doc/reference_manual')
-rw-r--r-- | system/doc/reference_manual/Makefile | 113 | ||||
-rw-r--r-- | system/doc/reference_manual/book.xml | 43 | ||||
-rw-r--r-- | system/doc/reference_manual/code_loading.xml | 158 | ||||
-rw-r--r-- | system/doc/reference_manual/data_types.xml | 399 | ||||
-rw-r--r-- | system/doc/reference_manual/distributed.xml | 279 | ||||
-rw-r--r-- | system/doc/reference_manual/errors.xml | 217 | ||||
-rw-r--r-- | system/doc/reference_manual/expressions.xml | 1422 | ||||
-rw-r--r-- | system/doc/reference_manual/functions.xml | 168 | ||||
-rw-r--r-- | system/doc/reference_manual/introduction.xml | 155 | ||||
-rw-r--r-- | system/doc/reference_manual/macros.xml | 211 | ||||
-rw-r--r-- | system/doc/reference_manual/make.dep | 16 | ||||
-rw-r--r-- | system/doc/reference_manual/modules.xml | 254 | ||||
-rw-r--r-- | system/doc/reference_manual/part.xml | 44 | ||||
-rw-r--r-- | system/doc/reference_manual/patterns.xml | 59 | ||||
-rw-r--r-- | system/doc/reference_manual/ports.xml | 159 | ||||
-rw-r--r-- | system/doc/reference_manual/processes.xml | 205 | ||||
-rw-r--r-- | system/doc/reference_manual/records.xml | 169 | ||||
-rw-r--r-- | system/doc/reference_manual/xmlfiles.mk | 33 |
18 files changed, 4104 insertions, 0 deletions
diff --git a/system/doc/reference_manual/Makefile b/system/doc/reference_manual/Makefile new file mode 100644 index 0000000000..34e5b7f555 --- /dev/null +++ b/system/doc/reference_manual/Makefile @@ -0,0 +1,113 @@ +# +# %CopyrightBegin% +# +# Copyright Ericsson AB 2003-2009. All Rights Reserved. +# +# The contents of this file are subject to the Erlang Public License, +# Version 1.1, (the "License"); you may not use this file except in +# compliance with the License. You should have received a copy of the +# Erlang Public License along with this software. If not, it can be +# retrieved online at http://www.erlang.org/. +# +# Software distributed under the License is distributed on an "AS IS" +# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See +# the License for the specific language governing rights and limitations +# under the License. +# +# %CopyrightEnd% +# +# +include $(ERL_TOP)/make/target.mk +include $(ERL_TOP)/make/$(TARGET)/otp.mk + +# ---------------------------------------------------- +# Application version +# ---------------------------------------------------- +include $(ERL_TOP)/erts/vsn.mk +#VSN=$(SYSTEM_VSN) + +APPLICATION=otp-system-documentation +# ---------------------------------------------------- +# Release directory specification +# ---------------------------------------------------- +RELSYSDIR = $(RELEASE_PATH)/doc/reference_manual + +# ---------------------------------------------------- +# Target Specs +# ---------------------------------------------------- +XML_PART_FILES = part.xml + +include xmlfiles.mk +XML_CHAPTER_FILES=$(REF_MAN_CHAPTER_FILES) + +TOPDOCDIR=.. + +BOOK_FILES = book.xml + +GIF_FILES= + + +XML_FILES = \ + $(BOOK_FILES) $(XML_CHAPTER_FILES) \ + $(XML_PART_FILES) +# ---------------------------------------------------- + +C_FILES = + +ERL_FILES = + +HRL_FILES = + +HTML_FILES = \ + $(XML_PART_FILES:%.xml=%.html) + +HTMLDIR = ../html/reference_manual + +EXTRA_FILES = $(DEFAULT_GIF_FILES) \ + $(DEFAULT_HTML_FILES) \ + $(C_FILES) \ + $(ERL_FILES) \ + $(HRL_FILES) \ + $(MISC_FILES) \ + $(XML_CHAPTER_FILES:%.xml=%.html) + +HTML_UG_FILE = $(HTMLDIR)/users_guide.html + +# ---------------------------------------------------- +# FLAGS +# ---------------------------------------------------- +XML_FLAGS += +DVIPS_FLAGS += + +# ---------------------------------------------------- +# Targets +# ---------------------------------------------------- +docs: html + +local_docs: PDFDIR=../../pdf + +html: $(GIF_FILES) $(HTML_UG_FILE) + +debug opt: + +clean clean_docs: + rm -rf $(HTMLDIR) + rm -f $(TOP_PDF_FILE) $(TOP_PDF_FILE:%.pdf=%.fo) + rm -f errs core *~ + +# ---------------------------------------------------- +# Release Target +# ---------------------------------------------------- +include $(ERL_TOP)/make/otp_release_targets.mk + +release_docs_spec: docs +# $(INSTALL_DIR) $(RELEASE_PATH)/pdf +# $(INSTALL_DATA) $(TOP_PDF_FILE) $(RELEASE_PATH)/pdf + $(INSTALL_DIR) $(RELSYSDIR) + $(INSTALL_DATA) $(GIF_FILES) $(HTMLDIR)/*.html \ + $(RELSYSDIR) + +release_spec: + + + diff --git a/system/doc/reference_manual/book.xml b/system/doc/reference_manual/book.xml new file mode 100644 index 0000000000..eb2e860f80 --- /dev/null +++ b/system/doc/reference_manual/book.xml @@ -0,0 +1,43 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE book SYSTEM "book.dtd"> + +<book xmlns:xi="http://www.w3.org/2001/XInclude"> + <header titlestyle="normal"> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Erlang Reference Manual</title> + <prepared>Gunilla Arendt</prepared> + <docno></docno> + <date>2003-01-11</date> + <rev></rev> + <file></file> + </header> + <insidecover> + </insidecover> + <pagetext>Erlang Reference Manual</pagetext> + <preamble> + <contents level="2"></contents> + </preamble> + <parts lift="no"> + <xi:include href="part.xml"/> + </parts> + <listofterms></listofterms> + <index></index> +</book> + diff --git a/system/doc/reference_manual/code_loading.xml b/system/doc/reference_manual/code_loading.xml new file mode 100644 index 0000000000..8861b3bea5 --- /dev/null +++ b/system/doc/reference_manual/code_loading.xml @@ -0,0 +1,158 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Compilation and Code Loading</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>code_loading.xml</file> + </header> + <p>How code is compiled and loaded is not a language issue, but + is system dependent. This chapter describes compilation and + code loading in Erlang/OTP with pointers to relevant parts of + the documentation.</p> + + <section> + <title>Compilation</title> + <p>Erlang programs must be <em>compiled</em> to object code. + The compiler can generate a new file which contains the object + code. The current abstract machine which runs the object code is + called BEAM, therefore the object files get the suffix + <c>.beam</c>. The compiler can also generate a binary which can + be loaded directly.</p> + <p>The compiler is located in the Kernel module <c>compile</c>, see + <c>compile(3)</c>.</p> + <pre> +compile:file(Module) +compile:file(Module, Options)</pre> + <p>The Erlang shell understands the command <c>c(Module)</c> which + both compiles and loads <c>Module</c>.</p> + <p>There is also a module <c>make</c> which provides a set of + functions similar to the UNIX type Make functions, see + <c>make(3)</c>.</p> + <p>The compiler can also be accessed from the OS prompt, see + <c>erl(1)</c>.</p> + <pre> +% erl -compile <input>Module1</input>...<input>ModuleN</input> +% erl -make</pre> + <p>The <c>erlc</c> program provides an even better way to compile + modules from the shell, see <c>erlc(1)</c>. It understands a + number of flags that can be used to define macros, add search + paths for include files, and more.</p> + <pre> +% erlc <input><flags></input> <input>File1.erl</input>...<input>FileN.erl</input></pre> + </section> + + <section> + <marker id="loading"></marker> + <title>Code Loading</title> + <p>The object code must be <em>loaded</em> into the Erlang runtime + system. This is handled by the <em>code server</em>, see + <c>code(3)</c>.</p> + <p>The code server loads code according to a code loading strategy + which is either <em>interactive</em> (default) or + <em>embedded</em>. In interactive mode, code are searched for in + a <em>code path</em> and loaded when first referenced. In + embedded mode, code is loaded at start-up according to a <em>boot script</em>. This is described in <em>System Principles</em>.</p> + </section> + + <section> + <title>Code Replacement</title> + <p>Erlang supports change of code in a running system. Code + replacement is done on module level.</p> + <p>The code of a module can exist in two variants in a system: + <em>current</em> and <em>old</em>. When a module is loaded into + the system for the first time, the code becomes 'current'. If then + a new instance of the module is loaded, the code of the previous + instance becomes 'old' and the new instance becomes 'current'.</p> + <p>Both old and current code is valid, and may be evaluated + concurrently. Fully qualified function calls always refer to + current code. Old code may still be evaluated because of processes + lingering in the old code.</p> + <p>If a third instance of the module is loaded, the code server will + remove (purge) the old code and any processes lingering in it will + be terminated. Then the third instance becomes 'current' and + the previously current code becomes 'old'.</p> + <p>To change from old code to current code, a process must make a + fully qualified function call. Example:</p> + <pre> +-module(m). +-export([loop/0]). + +loop() -> + receive + code_switch -> + m:loop(); + Msg -> + ... + loop() + end.</pre> + <p>To make the process change code, send the message + <c>code_switch</c> to it. The process then will make a fully + qualified call to <c>m:loop()</c> and change to current code. + Note that <c>m:loop/0</c> must be exported.</p> + <p>For code replacement of funs to work, the tuple syntax + <c>{Module,FunctionName}</c> must be used to represent the fun.</p> + </section> + + <section> + <title>Running a function when a module is loaded</title> + + <warning> + <p>This section describes an experimental feature introduced in R13B03. + There may be backward-incompatible changes in the feature in future releases.</p> + </warning> + + <p>The <c>-on_load()</c> directive names a function that should + be run automatically when a module a loaded. Its syntax is:</p> + +<pre> +-on_load(Name/0).</pre> + + <p>It is not necessary to export the function. It will be called in a + freshly spawned process (which will be terminated as soon as the function + returns). The function must return <c>true</c> if the module is to + be remained loaded and be callable, or <c>false</c> if the module + is to be unloaded. Returning any other value or generating an exception + will also cause the module to be unloaded.</p> + + <p>A process that calls any function in a module whose <c>on_load</c> + function has not yet returned will be suspended until the <c>on_load</c> + function has returned.</p> + + <p>Example:</p> + + <pre> +-module(m). +-on_load(run_me/0). + +run_me() -> + %% Do something with side effects here, for instance load a library + %% containing native-implemented functions. + true.</pre> + + </section> + +</chapter> + diff --git a/system/doc/reference_manual/data_types.xml b/system/doc/reference_manual/data_types.xml new file mode 100644 index 0000000000..c85ac44165 --- /dev/null +++ b/system/doc/reference_manual/data_types.xml @@ -0,0 +1,399 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Data Types</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>data_types.xml</file> + </header> + + <section> + <title>Terms</title> + <p>Erlang provides a number of data types which are listed in this + chapter. A piece of data of any data type is called a + <em>term</em>.</p> + </section> + + <section> + <title>Number</title> + <p>There are two types of numeric literals, <em>integers</em> and + <em>floats</em>. Besides the conventional notation, there are two + Erlang-specific notations:</p> + <list type="bulleted"> + <item><c>$</c><em><c>char</c></em> <br></br> + + ASCII value of the character <em><c>char</c></em>.</item> + <item><em><c>base</c></em><c>#</c><em><c>value</c></em> <br></br> + + Integer with the base <em><c>base</c></em>, which must be an + integer in the range 2..36. <br></br> + + In Erlang 5.2/OTP R9B and earlier versions, the allowed range + is 2..16.</item> + </list> + <p>Examples:</p> + <pre> +1> <input>42.</input> +42 +2> <input>$A.</input> +65 +3> <input>$\ .</input> +10 +4> <input>2#101.</input> +5 +5> <input>16#1f.</input> +31 +6> <input>2.3.</input> +2.3 +7> <input>2.3e3.</input> +2.3e3 +8> <input>2.3e-3.</input> +0.0023</pre> + </section> + + <section> + <title>Atom</title> + <p>An atom is a literal, a constant with name. An atom should be + enclosed in single quotes (') if it does not begin with a + lower-case letter or if it contains other characters than + alphanumeric characters, underscore (_), or @.</p> + <p>Examples:</p> + <pre> +hello +phone_number +'Monday' +'phone number'</pre> + </section> + + <section> + <title>Bit Strings and Binaries</title> + <p>A bit string is used to store an area of untyped memory.</p> + <p>Bit Strings are expressed using the + <seealso marker="expressions#bit_syntax">bit syntax</seealso>.</p> + <p>Bit Strings which consists of a number of bits which is evenly + divisible by eight are called Binaries</p> + <p>Examples:</p> + <pre> +1> <input><<10,20>>.</input> +<<10,20>> +2> <input><<"ABC">>.</input> +<<"ABC">> +1> <input><<1:1,0:1>>.</input> +<<2:2>></pre> + <p>More examples can be found in Programming Examples.</p> + </section> + + <section> + <title>Reference</title> + <p>A reference is a term which is unique in an Erlang runtime + system, created by calling <c>make_ref/0</c>.</p> + </section> + + <section> + <title>Fun</title> + <p>A fun is a functional object. Funs make it possible to create + an anonymous function and pass the function itself -- not its + name -- as argument to other functions.</p> + <p>Example:</p> + <pre> +1> <input>Fun1 = fun (X) -> X+1 end.</input> +#Fun<erl_eval.6.39074546> +2> <input>Fun1(2).</input> +3</pre> + <p>Read more about funs in <seealso marker="expressions#funs">Fun Expressions</seealso>. More examples can be found in Programming + Examples.</p> + </section> + + <section> + <title>Port Identifier</title> + <p>A port identifier identifies an Erlang port. <c>open_port/2</c>, + which is used to create ports, will return a value of this type.</p> + <p>Read more about ports in <seealso marker="ports">Ports and Port Drivers</seealso>.</p> + </section> + + <section> + <title>Pid</title> + <p>A process identifier, pid, identifies a process. + <c>spawn/1,2,3,4</c>, <c>spawn_link/1,2,3,4</c> and + <c>spawn_opt/4</c>, which are used to create processes, return + values of this type. Example:</p> + <pre> +1> <input>spawn(m, f, []).</input> +<0.51.0></pre> + <p>The BIF <c>self()</c> returns the pid of the calling process. + Example:</p> + <pre> +-module(m). +-export([loop/0]). + +loop() -> + receive + who_are_you -> + io:format("I am ~p~n", [self()]), + loop() + end. + +1> <input>P = spawn(m, loop, []).</input> +<0.58.0> +2> <input>P ! who_are_you.</input> +I am <0.58.0> +who_are_you</pre> + <p>Read more about processes in + <seealso marker="processes">Processes</seealso>.</p> + </section> + + <section> + <title>Tuple</title> + <p>Compound data type with a fixed number of terms:</p> + <pre> +{Term1,...,TermN}</pre> + <p>Each term <c>Term</c> in the tuple is called an + <em>element</em>. The number of elements is said to be + the <em>size</em> of the tuple.</p> + <p>There exists a number of BIFs to manipulate tuples.</p> + <p>Examples:</p> + <pre> +1> <input>P = {adam,24,{july,29}}.</input> +{adam,24,{july,29}} +2> <input>element(1,P).</input> +adam +3> <input>element(3,P).</input> +{july,29} +4> <input>P2 = setelement(2,P,25).</input> +{adam,25,{july,29}} +5> <input>tuple_size(P).</input> +3 +6> <input>tuple_size({}).</input> +0</pre> + </section> + + <section> + <title>List</title> + <p>Compound data type with a variable number of terms.</p> + <pre> +[Term1,...,TermN]</pre> + <p>Each term <c>Term</c> in the list is called an + <em>element</em>. The number of elements is said to be + the <em>length</em> of the list.</p> + <p>Formally, a list is either the empty list <c>[]</c> or + consists of a <em>head</em> (first element) and a <em>tail</em> + (remainder of the list) which is also a list. The latter can + be expressed as <c>[H|T]</c>. The notation + <c>[Term1,...,TermN]</c> above is actually shorthand for + the list <c>[Term1|[...|[TermN|[]]]]</c>.</p> + <p>Example: <br></br> +<c>[]</c> is a list, thus <br></br> +<c>[c|[]]</c> is a list, thus <br></br> +<c>[b|[c|[]]]</c> is a list, thus <br></br> +<c>[a|[b|[c|[]]]]</c> is a list, or in short <c>[a,b,c]</c>.</p> + <p></p> + <p>A list where the tail is a list is sometimes called a <em>proper list</em>. It is allowed to have a list where the tail is not a + list, for example <c>[a|b]</c>. However, this type of list is of + little practical use.</p> + <p>Examples:</p> + <pre> +1> <input>L1 = [a,2,{c,4}].</input> +[a,2,{c,4}] +2> <input>[H|T] = L1.</input> +[a,2,{c,4}] +3> <input>H.</input> +a +4> <input>T.</input> +[2,{c,4}] +5> <input>L2 = [d|T].</input> +[d,2,{c,4}] +6> <input>length(L1).</input> +3 +7> <input>length([]).</input> +0</pre> + <p>A collection of list processing functions can be found in + the STDLIB module <c>lists</c>.</p> + </section> + + <section> + <title>String</title> + <p>Strings are enclosed in double quotes ("), but is not a + data type in Erlang. Instead a string <c>"hello"</c> is + shorthand for the list <c>[$h,$e,$l,$l,$o]</c>, that is + <c>[104,101,108,108,111]</c>.</p> + <p>Two adjacent string literals are concatenated into one. This is + done at compile-time and does not incur any runtime overhead. + Example:</p> + <pre> +"string" "42"</pre> + <p>is equivalent to</p> + <pre> +"string42"</pre> + </section> + + <section> + <title>Record</title> + <p>A record is a data structure for storing a fixed number of + elements. It has named fields and is similar to a struct in C. + However, record is not a true data type. Instead record + expressions are translated to tuple expressions during + compilation. Therefore, record expressions are not understood by + the shell unless special actions are taken. See <c>shell(3)</c> + for details.</p> + <p>Examples:</p> + <pre> +-module(person). +-export([new/2]). + +-record(person, {name, age}). + +new(Name, Age) -> + #person{name=Name, age=Age}. + +1> <input>person:new(ernie, 44).</input> +{person,ernie,44}</pre> + <p>Read more about records in + <seealso marker="records">Records</seealso>. More examples can be + found in Programming Examples.</p> + </section> + + <section> + <title>Boolean</title> + <p>There is no Boolean data type in Erlang. Instead the atoms + <c>true</c> and <c>false</c> are used to denote Boolean values.</p> + <p>Examples:</p> + <pre> +1> <input>2 =< 3</input>. +true +2> <input>true or false</input>. +true</pre> + </section> + + <section> + <title>Escape Sequences</title> + <p>Within strings and quoted atoms, the following escape sequences + are recognized:</p> + <table> + <row> + <cell align="left" valign="middle"><em>Sequence</em></cell> + <cell align="left" valign="middle"><em>Description</em></cell> + </row> + <row> + <cell align="left" valign="middle">\\b</cell> + <cell align="left" valign="middle">backspace</cell> + </row> + <row> + <cell align="left" valign="middle">\\d</cell> + <cell align="left" valign="middle">delete</cell> + </row> + <row> + <cell align="left" valign="middle">\\e</cell> + <cell align="left" valign="middle">escape</cell> + </row> + <row> + <cell align="left" valign="middle">\\f</cell> + <cell align="left" valign="middle">form feed</cell> + </row> + <row> + <cell align="left" valign="middle">\</cell> + <cell align="left" valign="middle">newline</cell> + </row> + <row> + <cell align="left" valign="middle">\\r</cell> + <cell align="left" valign="middle">carriage return</cell> + </row> + <row> + <cell align="left" valign="middle">\\s</cell> + <cell align="left" valign="middle">space</cell> + </row> + <row> + <cell align="left" valign="middle">\\t</cell> + <cell align="left" valign="middle">tab</cell> + </row> + <row> + <cell align="left" valign="middle">\\v</cell> + <cell align="left" valign="middle">vertical tab</cell> + </row> + <row> + <cell align="left" valign="middle">\\XYZ, \\YZ, \\Z</cell> + <cell align="left" valign="middle">character with octal representation XYZ, YZ or Z</cell> + </row> + <row> + <cell align="left" valign="middle">\\xXY</cell> + <cell align="left" valign="middle">character with hexadecimal representation XY</cell> + </row> + <row> + <cell align="left" valign="middle">\\x{X...}</cell> + <cell align="left" valign="middle">character with hexadecimal representation; X... is one or more hexadecimal characters</cell> + </row> + <row> + <cell align="left" valign="middle">\\^a...\\^z <br></br> +\\^A...\\^Z</cell> + <cell align="left" valign="middle">control A to control Z</cell> + </row> + <row> + <cell align="left" valign="middle">\\'</cell> + <cell align="left" valign="middle">single quote</cell> + </row> + <row> + <cell align="left" valign="middle">\\"</cell> + <cell align="left" valign="middle">double quote</cell> + </row> + <row> + <cell align="left" valign="middle">\\\\</cell> + <cell align="left" valign="middle">backslash</cell> + </row> + <tcaption>Recognized Escape Sequences.</tcaption> + </table> + </section> + + <section> + <title>Type Conversions</title> + <p>There are a number of BIFs for type conversions. Examples:</p> + <pre> +1> <input>atom_to_list(hello).</input> +"hello" +2> <input>list_to_atom("hello").</input> +hello +3> <input>binary_to_list(<<"hello">>).</input> +"hello" +4> <input>binary_to_list(<<104,101,108,108,111>>).</input> +"hello" +5> <input>list_to_binary("hello").</input> +<<104,101,108,108,111>> +6> <input>float_to_list(7.0).</input> +"7.00000000000000000000e+00" +7> <input>list_to_float("7.000e+00").</input> +7.0 +8> <input>integer_to_list(77).</input> +"77" +9> <input>list_to_integer("77").</input> +77 +10> <input>tuple_to_list({a,b,c}).</input> +[a,b,c] +11> <input>list_to_tuple([a,b,c]).</input> +{a,b,c} +12> <input>term_to_binary({a,b,c}).</input> +<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>> +13> <input>binary_to_term(<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>).</input> +{a,b,c}</pre> + </section> +</chapter> + diff --git a/system/doc/reference_manual/distributed.xml b/system/doc/reference_manual/distributed.xml new file mode 100644 index 0000000000..52222c6d9d --- /dev/null +++ b/system/doc/reference_manual/distributed.xml @@ -0,0 +1,279 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Distributed Erlang</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>distributed.xml</file> + </header> + + <section> + <title>Distributed Erlang System</title> + <p>A <em>distributed Erlang system</em> consists of a number of + Erlang runtime systems communicating with each other. Each such + runtime system is called a <em>node</em>. Message passing between + processes at different nodes, as well as links and monitors, are + transparent when pids are used. Registered names, however, are + local to each node. This means the node must be specified as well + when sending messages etc. using registered names.</p> + <p>The distribution mechanism is implemented using TCP/IP sockets. + How to implement an alternative carrier is described in <em>ERTS User's Guide</em>.</p> + </section> + + <section> + <title>Nodes</title> + <p>A <em>node</em> is an executing Erlang runtime system which has + been given a name, using the command line flag <c>-name</c> + (long names) or <c>-sname</c> (short names).</p> + <p>The format of the node name is an atom <c>name@host</c> where + <c>name</c> is the name given by the user and <c>host</c> is + the full host name if long names are used, or the first part of + the host name if short names are used. <c>node()</c> returns + the name of the node. Example:</p> + <pre> +% <input>erl -name dilbert</input> +([email protected])1> <input>node().</input> + +% <input>erl -sname dilbert</input> +(dilbert@uab)1> <input>node().</input> +dilbert@uab</pre> + <note> + <p>A node with a long node name cannot communicate with a node + with a short node name.</p> + </note> + </section> + + <section> + <title>Node Connections</title> + <p>The nodes in a distributed Erlang system are loosely connected. + The first time the name of another node is used, for example if + <c>spawn(Node,M,F,A)</c> or <c>net_adm:ping(Node)</c> is called, + a connection attempt to that node will be made.</p> + <p>Connections are by default transitive. If a node A connects to + node B, and node B has a connection to node C, then node A will + also try to connect to node C. This feature can be turned off by + using the command line flag <c>-connect_all false</c>, see + <c>erl(1)</c>.</p> + <p>If a node goes down, all connections to that node are removed. + Calling <c>erlang:disconnect(Node)</c> will force disconnection + of a node.</p> + <p>The list of (visible) nodes currently connected to is returned by + <c>nodes()</c>.</p> + </section> + + <section> + <title>epmd</title> + <p>The Erlang Port Mapper Daemon <em>epmd</em> is automatically + started at every host where an Erlang node is started. It is + responsible for mapping the symbolic node names to machine + addresses. See <c>epmd(1)</c>.</p> + </section> + + <section> + <title>Hidden Nodes</title> + <p>In a distributed Erlang system, it is sometimes useful to + connect to a node without also connecting to all other nodes. + An example could be some kind of O&M functionality used to + inspect the status of a system without disturbing it. For this + purpose, a <em>hidden node</em> may be used.</p> + <p>A hidden node is a node started with the command line flag + <c>-hidden</c>. Connections between hidden nodes and other nodes + are not transitive, they must be set up explicitly. Also, hidden + nodes does not show up in the list of nodes returned by + <c>nodes()</c>. Instead, <c>nodes(hidden)</c> or + <c>nodes(connected)</c> must be used. This means, for example, + that the hidden node will not be added to the set of nodes that + <c>global</c> is keeping track of.</p> + <p>This feature was added in Erlang 5.0/OTP R7.</p> + </section> + + <section> + <title>C Nodes</title> + <p>A <em>C node</em> is a C program written to act as a hidden node + in a distributed Erlang system. The library <em>Erl_Interface</em> + contains functions for this purpose. Refer to the documentation + for Erl_Interface and <em>Interoperability Tutorial</em> for more + information about C nodes.</p> + </section> + + <section> + <title>Security</title> + <p>Authentication determines which nodes are allowed to communicate + with each other. In a network of different Erlang nodes, it is + built into the system at the lowest possible level. Each node has + its own <em>magic cookie</em>, which is an Erlang atom.</p> + <p>When a nodes tries to connect to another node, the magic cookies + are compared. If they do not match, the connected node rejects + the connection.</p> + <p>At start-up, a node has a random atom assigned as its magic + cookie and the cookie of other nodes is assumed to be + <c>nocookie</c>. The first action of the Erlang network + authentication server (<c>auth</c>) is then to read a file named + <c>$HOME/.erlang.cookie</c>. If the file does not exist, it is + created. The UNIX permissions mode of the file is set to octal + 400 (read-only by user) and its contents are a random string. An + atom <c>Cookie</c> is created from the contents of the file and + the cookie of the local node is set to this using + <c>erlang:set_cookie(node(), Cookie)</c>. This also makes + the local node assume that all other nodes have the same cookie + <c>Cookie</c>.</p> + <p>Thus, groups of users with identical cookie files get Erlang + nodes which can communicate freely and without interference from + the magic cookie system. Users who want run nodes on separate + file systems must make certain that their cookie files are + identical on the different file systems.</p> + <p>For a node <c>Node1</c> with magic cookie <c>Cookie</c> to be + able to connect to, or accept a connection from, another node + <c>Node2</c> with a different cookie <c>DiffCookie</c>, + the function <c>erlang:set_cookie(Node2, DiffCookie)</c> must + first be called at <c>Node1</c>. Distributed systems with + multiple user IDs can be handled in this way.</p> + <p>The default when a connection is established between two nodes, + is to immediately connect all other visible nodes as well. This + way, there is always a fully connected network. If there are + nodes with different cookies, this method might be inappropriate + and the command line flag <c>-connect_all false</c> must be set, + see <seealso marker="erts:erl">erl(1)</seealso>.</p> + <p>The magic cookie of the local node is retrieved by calling + <c>erlang:get_cookie()</c>.</p> + </section> + + <section> + <title>Distribution BIFs</title> + <p>Some useful BIFs for distributed programming, see + <c>erlang(3)</c> for more information:</p> + <table> + <row> + <cell align="left" valign="middle"><c>erlang:disconnect_node(Node)</c></cell> + <cell align="left" valign="middle">Forces the disconnection of a node.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>erlang:get_cookie()</c></cell> + <cell align="left" valign="middle">Returns the magic cookie of the current node.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_alive()</c></cell> + <cell align="left" valign="middle">Returns <c>true</c>if the runtime system is a node and can connect to other nodes, <c>false</c>otherwise.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>monitor_node(Node, true|false)</c></cell> + <cell align="left" valign="middle">Monitor the status of <c>Node</c>. A message<c>{nodedown, Node}</c>is received if the connection to it is lost.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>node()</c></cell> + <cell align="left" valign="middle">Returns the name of the current node. Allowed in guards.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>node(Arg)</c></cell> + <cell align="left" valign="middle">Returns the node where <c>Arg</c>, a pid, reference, or port, is located.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>nodes()</c></cell> + <cell align="left" valign="middle">Returns a list of all visible nodes this node is connected to.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>nodes(Arg)</c></cell> + <cell align="left" valign="middle">Depending on <c>Arg</c>, this function can return a list not only of visible nodes, but also hidden nodes and previously known nodes, etc.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>set_cookie(Node, Cookie)</c></cell> + <cell align="left" valign="middle">Sets the magic cookie used when connecting to <c>Node</c>. If <c>Node</c>is the current node, <c>Cookie</c>will be used when connecting to all new nodes.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>spawn[_link|_opt](Node, Fun)</c></cell> + <cell align="left" valign="middle">Creates a process at a remote node.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>spawn[_link|opt](Node, Module, FunctionName, Args)</c></cell> + <cell align="left" valign="middle">Creates a process at a remote node.</cell> + </row> + <tcaption>Distribution BIFs.</tcaption> + </table> + </section> + + <section> + <title>Distribution Command Line Flags</title> + <p>Examples of command line flags used for distributed programming, + see <c>erl(1)</c> for more information:</p> + <table> + <row> + <cell align="left" valign="middle"><c>-connect_all false</c></cell> + <cell align="left" valign="middle">Only explicit connection set-ups will be used.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>-hidden</c></cell> + <cell align="left" valign="middle">Makes a node into a hidden node.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>-name Name</c></cell> + <cell align="left" valign="middle">Makes a runtime system into a node, using long node names.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>-setcookie Cookie</c></cell> + <cell align="left" valign="middle">Same as calling <c>erlang:set_cookie(node(), Cookie)</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>-sname Name</c></cell> + <cell align="left" valign="middle">Makes a runtime system into a node, using short node names.</cell> + </row> + <tcaption>Distribution Command Line Flags.</tcaption> + </table> + </section> + + <section> + <title>Distribution Modules</title> + <p>Examples of modules useful for distributed programming:</p> + <p>In Kernel:</p> + <table> + <row> + <cell align="left" valign="middle"><c>global</c></cell> + <cell align="left" valign="middle">A global name registration facility.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>global_group</c></cell> + <cell align="left" valign="middle">Grouping nodes to global name registration groups.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>net_adm</c></cell> + <cell align="left" valign="middle">Various Erlang net administration routines.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>net_kernel</c></cell> + <cell align="left" valign="middle">Erlang networking kernel.</cell> + </row> + <tcaption>Kernel Modules Useful For Distribution.</tcaption> + </table> + <p>In STDLIB:</p> + <table> + <row> + <cell align="left" valign="middle"><c>slave</c></cell> + <cell align="left" valign="middle">Start and control of slave nodes.</cell> + </row> + <tcaption>STDLIB Modules Useful For Distribution.</tcaption> + </table> + </section> +</chapter> + diff --git a/system/doc/reference_manual/errors.xml b/system/doc/reference_manual/errors.xml new file mode 100644 index 0000000000..02885a3813 --- /dev/null +++ b/system/doc/reference_manual/errors.xml @@ -0,0 +1,217 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Errors and Error Handling</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>errors.xml</file> + </header> + + <section> + <title>Terminology</title> + <p>Errors can roughly be divided into four different types:</p> + <list type="bulleted"> + <item>Compile-time errors</item> + <item>Logical errors</item> + <item>Run-time errors</item> + <item>Generated errors</item> + </list> + <p>A compile-time error, for example a syntax error, should not + cause much trouble as it is caught by the compiler.</p> + <p>A logical error is when a program does not behave as intended, + but does not crash. An example could be that nothing happens when + a button in a graphical user interface is clicked.</p> + <p>A run-time error is when a crash occurs. An example could be + when an operator is applied to arguments of the wrong type. + The Erlang programming language has built-in features for + handling of run-time errors.</p> + <p>A run-time error can also be emulated by calling + <c>erlang:error(Reason)</c>, <c>erlang:error(Reason, Args)</c> + (those appeared in Erlang 5.4/OTP-R10), + <c>erlang:fault(Reason)</c> or <c>erlang:fault(Reason, Args)</c> + (old equivalents).</p> + <p>A run-time error is another name for an exception + of class <c>error</c>. + </p> + <p>A generated error is when the code itself calls + <c>exit/1</c> or <c>throw/1</c>. Note that emulated run-time + errors are not denoted as generated errors here. + </p> + <p>Generated errors are exceptions of classes <c>exit</c> and + <c>throw</c>. + </p> + <p>When a run-time error or generated error occurs in Erlang, + execution for the process which evaluated + the erroneous expression is stopped. + This is referred to as a <em>failure</em>, that execution or + evaluation <em>fails</em>, or that the process <em>fails</em>, + <em>terminates</em> or <em>exits</em>. Note that a process may + terminate/exit for other reasons than a failure.</p> + <p>A process that terminates will emit an <em>exit signal</em> with + an <em>exit reason</em> that says something about which error + has occurred. Normally, some information about the error will + be printed to the terminal.</p> + </section> + + <section> + <title>Exceptions</title> + <p>Exceptions are run-time errors or generated errors and + are of three different classes, with different origins. The + <seealso marker="expressions#try">try</seealso> expression + (appeared in Erlang 5.4/OTP-R10B) + can distinguish between the different classes, whereas the + <seealso marker="expressions#catch">catch</seealso> + expression can not. They are described in the Expressions chapter.</p> + <table> + <row> + <cell align="left" valign="middle"><em>Class</em></cell> + <cell align="left" valign="middle"><em>Origin</em></cell> + </row> + <row> + <cell align="left" valign="middle"><c>error</c></cell> + <cell align="left" valign="middle">Run-time error for example <c>1+a</c>, or the process called <c>erlang:error/1,2</c> (appeared in Erlang 5.4/OTP-R10B) or <c>erlang:fault/1,2</c> (old equivalent)</cell> + </row> + <row> + <cell align="left" valign="middle"><c>exit</c></cell> + <cell align="left" valign="middle">The process called <c>exit/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>throw</c></cell> + <cell align="left" valign="middle">The process called <c>throw/1</c></cell> + </row> + <tcaption>Exception Classes.</tcaption> + </table> + <p>An exception consists of its class, an exit reason + (the <seealso marker="#exit_reasons">Exit Reason</seealso>), + and a stack trace (that aids in finding the code location of + the exception).</p> + <p>The stack trace can be retrieved using + <c>erlang:get_stacktrace/0</c> (new in Erlang 5.4/OTP-R10B + from within a <c>try</c> expression, and is returned for + exceptions of class <c>error</c> from a <c>catch</c> expression.</p> + <p>An exception of class <c>error</c> is also known as a run-time + error.</p> + </section> + + <section> + <title>Handling of Run-Time Errors in Erlang</title> + + <section> + <title>Error Handling Within Processes</title> + <p>It is possible to prevent run-time errors and other + exceptions from causing + the process to terminate by using <c>catch</c> or + <c>try</c>, see the Expressions chapter about + <seealso marker="expressions#catch">Catch</seealso> + and <seealso marker="expressions#try">Try</seealso>.</p> + </section> + + <section> + <title>Error Handling Between Processes</title> + <p>Processes can monitor other processes and detect process + terminations, see + the <seealso marker="processes#errors">Processes</seealso> + chapter.</p> + </section> + </section> + + <section> + <marker id="exit_reasons"></marker> + <title>Exit Reasons</title> + <p>When a run-time error occurs, + that is an exception of class <c>error</c>, + the exit reason is a tuple <c>{Reason,Stack}</c>. + <c>Reason</c> is a term indicating the type of error:</p> + <table> + <row> + <cell align="left" valign="middle"><em>Reason</em></cell> + <cell align="left" valign="middle"><em>Type of error</em></cell> + </row> + <row> + <cell align="left" valign="middle"><c>badarg</c></cell> + <cell align="left" valign="middle">Bad argument. The argument is of wrong data type, or is otherwise badly formed.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>badarith</c></cell> + <cell align="left" valign="middle">Bad argument in an arithmetic expression.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{badmatch,V}</c></cell> + <cell align="left" valign="middle">Evaluation of a match expression failed. The value <c>V</c> did not match.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>function_clause</c></cell> + <cell align="left" valign="middle">No matching function clause is found when evaluating a function call.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{case_clause,V}</c></cell> + <cell align="left" valign="middle">No matching branch is found when evaluating a <c>case</c> expression. The value <c>V</c> did not match.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>if_clause</c></cell> + <cell align="left" valign="middle">No true branch is found when evaluating an <c>if</c> expression.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{try_clause,V}</c></cell> + <cell align="left" valign="middle">No matching branch is found when evaluating the of-section of a <c>try</c> expression. The value <c>V</c> did not match.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>undef</c></cell> + <cell align="left" valign="middle">The function cannot be found when evaluating a function call.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{badfun,F}</c></cell> + <cell align="left" valign="middle">There is something wrong with a fun <c>F</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{badarity,F}</c></cell> + <cell align="left" valign="middle">A fun is applied to the wrong number of arguments. <c>F</c> describes the fun and the arguments.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>timeout_value</c></cell> + <cell align="left" valign="middle">The timeout value in a <c>receive..after</c> expression is evaluated to something else than an integer or <c>infinity</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>noproc</c></cell> + <cell align="left" valign="middle">Trying to link to a non-existing process.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{nocatch,V}</c></cell> + <cell align="left" valign="middle">Trying to evaluate a <c>throw </c>outside a <c>catch</c>. <c>V</c> is the thrown term.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>system_limit</c></cell> + <cell align="left" valign="middle">A system limit has been reached. See Efficiency Guide for information about system limits.</cell> + </row> + <tcaption>Exit Reasons.</tcaption> + </table> + <p><c>Stack</c> is the stack of function calls being evaluated + when the error occurred, given as a list of tuples + <c>{Module,Name,Arity}</c> with the most recent function call + first. The most recent function call tuple may in some + cases be <c>{Module,Name,[Arg]}</c>.</p> + </section> +</chapter> + diff --git a/system/doc/reference_manual/expressions.xml b/system/doc/reference_manual/expressions.xml new file mode 100644 index 0000000000..fa7870d96c --- /dev/null +++ b/system/doc/reference_manual/expressions.xml @@ -0,0 +1,1422 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Expressions</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>expressions.xml</file> + </header> + <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: <seealso marker="macros">Macros</seealso> and + <seealso marker="records">Records</seealso>.</p> + + <section> + <title>Expression Evaluation</title> + <p>All subexpressions are evaluated before an expression itself is + evaluated, unless explicitly stated otherwise. For example, + consider the expression:</p> + <code type="none"> +Expr1 + Expr2</code> + <p><c>Expr1</c> and <c>Expr2</c>, 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 <c>badarg</c> run-time error.</p> + </section> + + <section> + <marker id="term"></marker> + <title>Terms</title> + <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> + </section> + + <section> + <title>Variables</title> + <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> + <pre> +X +Name1 +PhoneNumber +Phone_number +_ +_Height</pre> + <p>Variables are bound to values using + <seealso marker="patterns">pattern matching</seealso>. Erlang + uses <em>single assignment</em>, a variable can only be bound + once.</p> + <p>The <em>anonymous variable</em> is denoted by underscore (_) and + can be used when a variable is required but its value can be + ignored. Example:</p> + <pre> +[H|_] = [1,2,3]</pre> + <p>Variables starting with underscore (_), for example + <c>_Height</c>, 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> + <pre> +member(_, []) -> + [].</pre> + <p>can be rewritten to be more readable:</p> + <pre> +member(Elem, []) -> + [].</pre> + <p>This will however cause a warning for an unused variable + <c>Elem</c>, if the code is compiled with the flag + <c>warn_unused_vars</c> set. Instead, the code can be rewritten + to:</p> + <pre> +member(_Elem, []) -> + [].</pre> + <p>Note that since variables starting with an underscore are + not anonymous, this will match:</p> + <pre> +{_,_} = {1,2}</pre> + <p>But this will fail:</p> + <pre> +{_N,_N} = {1,2}</pre> + <p>The scope for a variable is its function clause. + Variables bound in a branch of an <c>if</c>, <c>case</c>, + or <c>receive</c> 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 <c>try</c> 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> + </section> + + <section> + <marker id="pattern"></marker> + <title>Patterns</title> + <p>A pattern has the same structure as a term but may contain + unbound variables. Example:</p> + <pre> +Name1 +[H|T] +{error,Reason}</pre> + <p>Patterns are allowed in clause heads, <c>case</c> and + <c>receive</c> expressions, and match expressions.</p> + + <section> + <title>Match Operator = in Patterns</title> + <p>If <c>Pattern1</c> and <c>Pattern2</c> are valid patterns, + then the following is also a valid pattern:</p> + <pre> +Pattern1 = Pattern2</pre> + <p>When matched against a term, both <c>Pattern1</c> and + <c>Pattern2</c> will be matched against the term. The idea + behind this feature is to avoid reconstruction of terms. + Example:</p> + <pre> +f({connect,From,To,Number,Options}, To) -> + Signal = {connect,From,To,Number,Options}, + ...; +f(Signal, To) -> + ignore.</pre> + <p>can instead be written as</p> + <pre> +f({connect,_,To,_,_} = Signal, To) -> + ...; +f(Signal, To) -> + ignore.</pre> + </section> + + <section> + <title>String Prefix in Patterns</title> + <p>When matching strings, the following is a valid pattern:</p> + <pre> +f("prefix" ++ Str) -> ...</pre> + <p>This is syntactic sugar for the equivalent, but harder to + read</p> + <pre> +f([$p,$r,$e,$f,$i,$x | Str]) -> ...</pre> + </section> + + <section> + <title>Expressions in Patterns</title> + <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> + <pre> +case {Value, Result} of + {?THRESHOLD+1, ok} -> ...</pre> + <p>This feature was added in Erlang 5.0/OTP R7.</p> + </section> + </section> + + <section> + <title>Match</title> + <pre> +Expr1 = Expr2</pre> + <p>Matches <c>Expr1</c>, a pattern, against <c>Expr2</c>. + If the matching succeeds, any unbound variable in the pattern + becomes bound and the value of <c>Expr2</c> is returned.</p> + <p>If the matching fails, a <c>badmatch</c> run-time error will + occur.</p> + <p>Examples:</p> + <pre> +1> <input>{A, B} = {answer, 42}.</input> +{answer,42} +2> <input>A.</input> +answer +3> <input>{C, D} = [1, 2].</input> +** exception error: no match of right hand side value [1,2]</pre> + </section> + + <section> + <marker id="calls"></marker> + <title>Function Calls</title> + <pre> +ExprF(Expr1,...,ExprN) +ExprM:ExprF(Expr1,...,ExprN)</pre> + <p>In the first form of function calls, + <c>ExprM:ExprF(Expr1,...,ExprN)</c>, each of <c>ExprM</c> and + <c>ExprF</c> must be an atom or an expression that evaluates to + an atom. The function is said to be called by using the + <em>fully qualified function name</em>. This is often referred + to as a <em>remote</em> or <em>external function call</em>. + Example:</p> + <code type="none"> +lists:keysearch(Name, 1, List)</code> + <p>In the second form of function calls, + <c>ExprF(Expr1,...,ExprN)</c>, <c>ExprF</c> must be an atom or + evaluate to a fun.</p> + <p>If <c>ExprF</c> is an atom the function is said to be called by + using the <em>implicitly qualified function name</em>. If + <c>ExprF/N</c> is the name of a function explicitly or + automatically imported from module <c>M</c>, then the call is + short for <c>M:ExprF(Expr1,...,ExprN)</c>. Otherwise, + <c>ExprF/N</c> must be a locally defined function. Examples:</p> + <code type="none"> +handle(Msg, State) +spawn(m, init, [])</code> + <p>Examples where ExprF is a fun:</p> + <code type="none"> +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]</code> + <p>To avoid possible ambiguities, the fully qualified function + name must be used when calling a function with the same name as + a BIF, and the compiler does not allow defining a function with + the same name as an explicitly imported function.</p> + <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 + <seealso marker="code_loading">Compilation and Code Loading</seealso>.</p> + <p>See also the chapter about + <seealso marker="functions#eval">Function Evaluation</seealso>.</p> + </section> + + <section> + <title>If</title> + <pre> +if + GuardSeq1 -> + Body1; + ...; + GuardSeqN -> + BodyN +end</pre> + <p>The branches of an <c>if</c>-expression are scanned sequentially + until a guard sequence <c>GuardSeq</c> which evaluates to true is + found. Then the corresponding <c>Body</c> (sequence of expressions + separated by ',') is evaluated.</p> + <p>The return value of <c>Body</c> is the return value of + the <c>if</c> expression.</p> + <p>If no guard sequence is true, an <c>if_clause</c> run-time error + will occur. If necessary, the guard expression <c>true</c> can be + used in the last branch, as that guard sequence is always true.</p> + <p>Example:</p> + <pre> +is_greater_than(X, Y) -> + if + X>Y -> + true; + true -> % works as an 'else' branch + false + end</pre> + </section> + + <section> + <marker id="case"></marker> + <title>Case</title> + <pre> +case Expr of + Pattern1 [when GuardSeq1] -> + Body1; + ...; + PatternN [when GuardSeqN] -> + BodyN +end</pre> + <p>The expression <c>Expr</c> is evaluated and the patterns + <c>Pattern</c> are sequentially matched against the result. If a + match succeeds and the optional guard sequence <c>GuardSeq</c> is + true, the corresponding <c>Body</c> is evaluated.</p> + <p>The return value of <c>Body</c> is the return value of + the <c>case</c> expression.</p> + <p>If there is no matching pattern with a true guard sequence, + a <c>case_clause</c> run-time error will occur.</p> + <p>Example:</p> + <pre> +is_valid_signal(Signal) -> + case Signal of + {signal, _What, _From, _To} -> + true; + {signal, _What, _To} -> + true; + _Else -> + false + end.</pre> + </section> + + <section> + <marker id="send"></marker> + <title>Send</title> + <pre> +Expr1 ! Expr2</pre> + <p>Sends the value of <c>Expr2</c> as a message to the process + specified by <c>Expr1</c>. The value of <c>Expr2</c> is also + the return value of the expression.</p> + <p><c>Expr1</c> must evaluate to a pid, a registered name (atom) or + a tuple <c>{Name,Node}</c>, where <c>Name</c> is an atom and + <c>Node</c> a node name, also an atom.</p> + <list type="bulleted"> + <item>If <c>Expr1</c> evaluates to a name, but this name is not + registered, a <c>badarg</c> run-time error will occur.</item> + <item>Sending a message to a pid never fails, even if the pid + identifies a non-existing process.</item> + <item>Distributed message sending, that is if <c>Expr1</c> + evaluates to a tuple <c>{Name,Node}</c> (or a pid located at + another node), also never fails.</item> + </list> + </section> + + <section> + <marker id="receive"></marker> + <title>Receive</title> + <pre> +receive + Pattern1 [when GuardSeq1] -> + Body1; + ...; + PatternN [when GuardSeqN] -> + BodyN +end</pre> + <p>Receives messages sent to the process using the send operator + (!). The patterns <c>Pattern</c> 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 <c>GuardSeq</c> is true, the corresponding + <c>Body</c> 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 <c>Body</c> is the return value of + the <c>receive</c> expression.</p> + <p><c>receive</c> 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> + <pre> +wait_for_onhook() -> + receive + onhook -> + disconnect(), + idle(); + {connect, B} -> + B ! {busy, self()}, + wait_for_onhook() + end.</pre> + <p>It is possible to augment the <c>receive</c> expression with a + timeout:</p> + <pre> +receive + Pattern1 [when GuardSeq1] -> + Body1; + ...; + PatternN [when GuardSeqN] -> + BodyN +after + ExprT -> + BodyT +end</pre> + <p><c>ExprT</c> should evaluate to an integer. The highest allowed + value is 16#ffffffff, that is, the value must fit in 32 bits. + <c>receive..after</c> works exactly as <c>receive</c>, except + that if no matching message has arrived within <c>ExprT</c> + milliseconds, then <c>BodyT</c> is evaluated instead and its + return value becomes the return value of the <c>receive..after</c> + expression.</p> + <p>Example:</p> + <pre> +wait_for_onhook() -> + receive + onhook -> + disconnect(), + idle(); + {connect, B} -> + B ! {busy, self()}, + wait_for_onhook() + after + 60000 -> + disconnect(), + error() + end.</pre> + <p>It is legal to use a <c>receive..after</c> expression with no + branches:</p> + <pre> +receive +after + ExprT -> + BodyT +end</pre> + <p>This construction will not consume any messages, only suspend + execution in the process for <c>ExprT</c> milliseconds and can be + used to implement simple timers.</p> + <p>Example:</p> + <pre> +timer() -> + spawn(m, timer, [self()]). + +timer(Pid) -> + receive + after + 5000 -> + Pid ! timeout + end.</pre> + <p>There are two special cases for the timeout value <c>ExprT</c>:</p> + <taglist> + <tag><c>infinity</c></tag> + <item>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.</item> + <tag>0</tag> + <item>If there is no matching message in the mailbox, the timeout + will occur immediately.</item> + </taglist> + </section> + + <section> + <title>Term Comparisons</title> + <pre> +Expr1 <input>op</input> Expr2</pre> + <table> + <row> + <cell align="left" valign="middle"><em>op</em></cell> + <cell align="left" valign="middle"><em>Description</em></cell> + </row> + <row> + <cell align="left" valign="middle">==</cell> + <cell align="left" valign="middle">equal to</cell> + </row> + <row> + <cell align="left" valign="middle">/=</cell> + <cell align="left" valign="middle">not equal to</cell> + </row> + <row> + <cell align="left" valign="middle">=<</cell> + <cell align="left" valign="middle">less than or equal to</cell> + </row> + <row> + <cell align="left" valign="middle"><</cell> + <cell align="left" valign="middle">less than</cell> + </row> + <row> + <cell align="left" valign="middle">>=</cell> + <cell align="left" valign="middle">greater than or equal to</cell> + </row> + <row> + <cell align="left" valign="middle">></cell> + <cell align="left" valign="middle">greater than</cell> + </row> + <row> + <cell align="left" valign="middle">=:=</cell> + <cell align="left" valign="middle">exactly equal to</cell> + </row> + <row> + <cell align="left" valign="middle">=/=</cell> + <cell align="left" valign="middle">exactly not equal to</cell> + </row> + <tcaption>Term Comparison Operators.</tcaption> + </table> + <p>The arguments may be of different data types. The following + order is defined:</p> + <pre> +number < atom < reference < fun < port < pid < tuple < list < bit string</pre> + <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>If one of the compared terms is an integer and the other a + float, the integer is first converted into a float, unless the + operator is one of =:= and =/=. If the integer is too big to fit + in a float no conversion is done, but the order is determined by + inspecting the sign of the numbers.</p> + <p>Returns the Boolean value of the expression, <c>true</c> or + <c>false</c>.</p> + <p>Examples:</p> + <pre> +1> <input>1==1.0.</input> +true +2> <input>1=:=1.0.</input> +false +3> <input>1 > a.</input> +false</pre> + </section> + + <section> + <title>Arithmetic Expressions</title> + <pre> +<input>op</input> Expr +Expr1 <input>op</input> Expr2</pre> + <table> + <row> + <cell align="left" valign="middle"><em>op</em></cell> + <cell align="left" valign="middle"><em>Description</em></cell> + <cell align="left" valign="middle"><em>Argument type</em></cell> + </row> + <row> + <cell align="left" valign="middle">+</cell> + <cell align="left" valign="middle">unary +</cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">-</cell> + <cell align="left" valign="middle">unary -</cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">+</cell> + <cell align="left" valign="middle"> </cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">-</cell> + <cell align="left" valign="middle"> </cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">*</cell> + <cell align="left" valign="middle"> </cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">/</cell> + <cell align="left" valign="middle">floating point division</cell> + <cell align="left" valign="middle">number</cell> + </row> + <row> + <cell align="left" valign="middle">bnot</cell> + <cell align="left" valign="middle">unary bitwise not</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">div</cell> + <cell align="left" valign="middle">integer division</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">rem</cell> + <cell align="left" valign="middle">integer remainder of X/Y</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">band</cell> + <cell align="left" valign="middle">bitwise and</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">bor</cell> + <cell align="left" valign="middle">bitwise or</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">bxor</cell> + <cell align="left" valign="middle">arithmetic bitwise xor</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">bsl</cell> + <cell align="left" valign="middle">arithmetic bitshift left</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <row> + <cell align="left" valign="middle">bsr</cell> + <cell align="left" valign="middle">bitshift right</cell> + <cell align="left" valign="middle">integer</cell> + </row> + <tcaption>Arithmetic Operators.</tcaption> + </table> + + <p>Examples:</p> + <pre> +1> <input>+1.</input> +1 +2> <input>-1.</input> +-1 +3> <input>1+1.</input> +2 +4> <input>4/2.</input> +2.0 +5> <input>5 div 2.</input> +2 +6> <input>5 rem 2.</input> +1 +7> <input>2#10 band 2#01.</input> +0 +8> <input>2#10 bor 2#01.</input> +3 +9> <input>a + 10.</input> +** exception error: bad argument in an arithmetic expression + in operator +/2 + called as a + 10 +10> <input>1 bsl (1 bsl 64).</input> +** exception error: a system limit has been reached + in operator bsl/2 + called as 1 bsl 18446744073709551616</pre> + </section> + + <section> + <title>Boolean Expressions</title> + <pre> +<input>op</input> Expr +Expr1 <input>op</input> Expr2</pre> + <table> + <row> + <cell align="left" valign="middle"><em>op</em></cell> + <cell align="left" valign="middle"><em>Description</em></cell> + </row> + <row> + <cell align="left" valign="middle">not</cell> + <cell align="left" valign="middle">unary logical not</cell> + </row> + <row> + <cell align="left" valign="middle">and</cell> + <cell align="left" valign="middle">logical and</cell> + </row> + <row> + <cell align="left" valign="middle">or</cell> + <cell align="left" valign="middle">logical or</cell> + </row> + <row> + <cell align="left" valign="middle">xor</cell> + <cell align="left" valign="middle">logical xor</cell> + </row> + <tcaption>Logical Operators.</tcaption> + </table> + <p>Examples:</p> + <pre> +1> <input>not true.</input> +false +2> <input>true and false.</input> +false +3> <input>true xor false.</input> +true +4> <input>true or garbage.</input> +** exception error: bad argument + in operator or/2 + called as true or garbage</pre> + </section> + + <section> + <title>Short-Circuit Expressions</title> + <pre> +Expr1 orelse Expr2 +Expr1 andalso Expr2</pre> + <p>Expressions where <c>Expr2</c> is evaluated only if + necessary. That is, <c>Expr2</c> is evaluated only if <c>Expr1</c> + evaluates to <c>false</c> in an <c>orelse</c> expression, or only + if <c>Expr1</c> evaluates to <c>true</c> in an <c>andalso</c> + expression. Returns either the value of <c>Expr1</c> (that is, + <c>true</c> or <c>false</c>) or the value of <c>Expr2</c> + (if <c>Expr2</c> was evaluated).</p> + + <p>Example 1:</p> + <pre> +case A >= -1.0 andalso math:sqrt(A+1) > B of</pre> + <p>This will work even if <c>A</c> is less than <c>-1.0</c>, + since in that case, <c>math:sqrt/1</c> is never evaluated.</p> + <p>Example 2:</p> + <pre> +OnlyOne = is_atom(L) orelse + (is_list(L) andalso length(L) == 1),</pre> + + <p>From R13A, <c>Expr2</c> is no longer required to evaluate to a + boolean value. As a consequence, <c>andalso</c> and <c>orelse</c> + are now tail-recursive. For instance, the following function is + tail-recursive in R13A and later:</p> + + <pre> +all(Pred, [Hd|Tail]) -> + Pred(Hd) andalso all(Pred, Tail); +all(_, []) -> + true.</pre> + </section> + + <section> + <title>List Operations</title> + <pre> +Expr1 ++ Expr2 +Expr1 -- Expr2</pre> + <p>The list concatenation operator <c>++</c> appends its second + argument to its first and returns the resulting list.</p> + <p>The list subtraction operator <c>--</c> 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> + <pre> +1> <input>[1,2,3]++[4,5].</input> +[1,2,3,4,5] +2> <input>[1,2,3,2,1,2]--[2,1,2].</input> +[3,1,2]</pre> + + <warning><p>The complexity of <c>A -- B</c> is + proportional to <c>length(A)*length(B)</c>, meaning that it + will be very slow if both <c>A</c> and <c>B</c> are + long lists.</p></warning> + </section> + + <section> + <marker id="bit_syntax"></marker> + <title>Bit Syntax Expressions</title> + <code type="none"><![CDATA[<<>> +<<E1,...,En>>]]></code> + <p>Each element <c>Ei</c> specifies a <em>segment</em> of + the bit string. Each element <c>Ei</c> is a value, followed by an + optional <em>size expression</em> and an optional <em>type specifier list</em>.</p> + <pre> +Ei = Value | + Value:Size | + Value/TypeSpecifierList | + Value:Size/TypeSpecifierList</pre> + <p>Used in a bit string construction, <c>Value</c> 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, <c>Value</c> must be a variable, + or an integer, float or string.</p> + + <p>Note that, for example, using a string literal as in + <c><![CDATA[<<"abc">>]]></c> is syntactic sugar for + <c><![CDATA[<<$a,$b,$c>>]]></c>.</p> + + <p>Used in a bit string construction, <c>Size</c> is an expression + which should evaluate to an integer.</p> + + <p>Used in a bit string matching, <c>Size</c> must be an integer or a + variable bound to an integer.</p> + + <p>The value of <c>Size</c> specifies the size of the segment in + units (see below). The default value depends on the type (see + below). For <c>integer</c> it is 8, for + <c>float</c> it is 64, for <c>binary</c> and <c>bitstring</c> 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 <c>utf8</c>, <c>utf16</c>, and <c>utf32</c> types, + <c>Size</c> must not be given. The size of the segment is implicitly + determined by the type and value itself.</p> + + <p><c>TypeSpecifierList</c> is a list of type specifiers, in any + order, separated by hyphens (-). Default values are used for any + omitted type specifiers.</p> + <taglist> + <tag><c>Type</c>= <c>integer</c> | <c>float</c> | <c>binary</c> | + <c>bytes</c> | <c>bitstring</c> | <c>bits</c> | + <c>utf8</c> | <c>utf16</c> | <c>utf32</c> </tag> + <item>The default is <c>integer</c>. <c>bytes</c> is a shorthand for + <c>binary</c> and <c>bits</c> is a shorthand for <c>bitstring</c>. + See below for more information about the <c>utf</c> types. + </item> + + <tag><c>Signedness</c>= <c>signed</c> | <c>unsigned</c></tag> + <item>Only matters for matching and when the type is <c>integer</c>. + The default is <c>unsigned</c>.</item> + + <tag><c>Endianness</c>= <c>big</c> | <c>little</c> | <c>native</c></tag> + <item>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 <c>integer</c>, + <c>utf16</c>, <c>utf32</c>, or <c>float</c>. The default is <c>big</c>. + </item> + + <tag><c>Unit</c>= <c>unit:IntegerLiteral</c></tag> + <item>The allowed range is 1..256. Defaults to 1 for <c>integer</c>, + <c>float</c> and <c>bitstring</c>, and to 8 for <c>binary</c>. + No unit specifier must be given for the types + <c>utf8</c>, <c>utf16</c>, and <c>utf32</c>. + </item> + </taglist> + <p>The value of <c>Size</c> multiplied with the unit gives + the number of bits. A segment of type <c>binary</c> must have + a size that is evenly divisible by 8.</p> + + <note><p>When constructing binaries, if the size <c>N</c> 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 <c>N</c> least + significant bits will be put into the binary.</p></note> + + <p>The types <c>utf8</c>, <c>utf16</c>, and <c>utf32</c> specifies + encoding/decoding of the <em>Unicode Transformation Format</em>s UTF-8, UTF-16, + and UTF-32, respectively.</p> + + <p>When constructing a segment of a <c>utf</c> type, <c>Value</c> + must be an integer in one of the ranges 0..16#D7FF, + 16#E000..16#FFFD, or 16#10000..16#10FFFF + (i.e. a valid Unicode code point). Construction + will fail with a <c>badarg</c> exception if <c>Value</c> is + outside the allowed ranges. The size of the resulting binary + segment depends on the type and/or <c>Value</c>. For <c>utf8</c>, + <c>Value</c> will be encoded in 1 through 4 bytes. For + <c>utf16</c>, <c>Value</c> will be encoded in 2 or 4 + bytes. Finally, for <c>utf32</c>, <c>Value</c> 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: <c><![CDATA[<<"abc"/utf8>>]]></c> + which is syntatic sugar for + <c><![CDATA[<<$a/utf8,$b/utf8,$c/utf8>>]]></c>.</p> + + <p>A successful match of a segment of a <c>utf</c> type results + in an integer in one of the ranges 0..16#D7FF, 16#E000..16#FFFD, + or 16#10000..16#10FFFF + (i.e. a valid Unicode code point). The match will fail if returned value + would fall outside those ranges.</p> + + <p>A segment of type <c>utf8</c> will match 1 to 4 bytes in the binary, + if the binary at the match position contains a valid UTF-8 sequence. + (See RFC-2279 or the Unicode standard.)</p> + + <p>A segment of type <c>utf16</c> 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 <c>utf32</c> may match 4 bytes in the binary in the + same way as an <c>integer</c> segment matching 32 bits. + The match will fail if the resulting integer is outside the legal ranges + mentioned above.</p> + + <p>Examples:</p> + <pre> +1> <input>Bin1 = <<1,17,42>>.</input> +<<1,17,42>> +2> <input>Bin2 = <<"abc">>.</input> +<<97,98,99>> +3> <input>Bin3 = <<1,17,42:16>>.</input> +<<1,17,0,42>> +4> <input><<A,B,C:16>> = <<1,17,42:16>>.</input> +<<1,17,0,42>> +5> <input>C.</input> +42 +6> <input><<D:16,E,F>> = <<1,17,42:16>>.</input> +<<1,17,0,42>> +7> <input>D.</input> +273 +8> <input>F.</input> +42 +9> <input><<G,H/binary>> = <<1,17,42:16>>.</input> +<<1,17,0,42>> +10> <input>H.</input> +<<17,0,42>> +11> <input><<G,H/bitstring>> = <<1,17,42:12>>.</input> +<<1,17,1,10:4>> +12> <input>H.</input> +<<17,1,10:4>> +13> <input><<1024/utf8>>.</input> +<<208,128>> +</pre> + <p>Note that bit string patterns cannot be nested.</p> + <p>Note also that "<c><![CDATA[B=<<1>>]]></c>" is interpreted as + "<c><![CDATA[B =<<1>>]]></c>" which is a syntax error. The correct way is + to write a space after '=': "<c><![CDATA[B= <<1>>]]></c>.</p> + <p>More examples can be found in <em>Programming Examples</em>.</p> + </section> + + <section> + <marker id="funs"></marker> + <title>Fun Expressions</title> + <pre> +fun + (Pattern11,...,Pattern1N) [when GuardSeq1] -> + Body1; + ...; + (PatternK1,...,PatternKN) [when GuardSeqK] -> + BodyK +end</pre> + <p>A fun expression begins with the keyword <c>fun</c> and ends + with the keyword <c>end</c>. Between them should be a function + declaration, similar to a + <seealso marker="functions#syntax">regular function declaration</seealso>, 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> + <pre> +1> <input>Fun1 = fun (X) -> X+1 end.</input> +#Fun<erl_eval.6.39074546> +2> <input>Fun1(2).</input> +3 +3> <input>Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.</input> +#Fun<erl_eval.6.39074546> +4> <input>Fun2(7).</input> +gt</pre> + <p>The following fun expressions are also allowed:</p> + <pre> +fun Name/Arity +fun Module:Name/Arity</pre> + <p>In <c>Name/Arity</c>, <c>Name</c> is an atom and <c>Arity</c> is an integer. + <c>Name/Arity</c> must specify an existing local function. The expression is + syntactic sugar for:</p> + <pre> +fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end</pre> + <p>In <c>Module:Name/Arity</c>, <c>Module</c> and <c>Name</c> are atoms + and <c>Arity</c> is an integer. + A fun defined in this way will refer to the function <c>Name</c> + with arity <c>Arity</c> in the <em>latest</em> version of module <c>Module</c>. + </p> + <p>When applied to a number N of arguments, a tuple + <c>{Module,FunctionName}</c> is interpreted as a fun, referring + to the function <c>FunctionName</c> with arity N in the module + <c>Module</c>. The function must be exported. + <em>This usage is deprecated.</em> + See <seealso marker="#calls">Function Calls</seealso> for an example.</p> + <p>More examples can be found in <em>Programming Examples</em>.</p> + </section> + + <section> + <marker id="catch"></marker> + <title>Catch and Throw</title> + <code type="none"> +catch Expr</code> + <p>Returns the value of <c>Expr</c> unless an exception + occurs during the evaluation. In that case, the exception is + caught. For exceptions of class <c>error</c>, + that is run-time errors: <c>{'EXIT',{Reason,Stack}}</c> + is returned. For exceptions of class <c>exit</c>, that is + the code called <c>exit(Term)</c>: <c>{'EXIT',Term}</c> is returned. + For exceptions of class <c>throw</c>, that is + the code called <c>throw(Term)</c>: <c>Term</c> is returned.</p> + <p><c>Reason</c> depends on the type of error that occurred, and + <c>Stack</c> is the stack of recent function calls, see + <seealso marker="errors#exit_reasons">Errors and Error Handling</seealso>.</p> + <p>Examples:</p> + <p></p> + <pre> +1> <input>catch 1+2.</input> +3 +2> <input>catch 1+a.</input> +{'EXIT',{badarith,[...]}}</pre> + <p>Note that <c>catch</c> has low precedence and catch + subexpressions often needs to be enclosed in a block + expression or in parenthesis:</p> + <pre> +3> <input>A = catch 1+2.</input> +** 1: syntax error before: 'catch' ** +4> <input>A = (catch 1+2).</input> +3</pre> + <p>The BIF <c>throw(Any)</c> can be used for non-local return from + a function. It must be evaluated within a <c>catch</c>, which will + return the value <c>Any</c>. Example:</p> + <pre> +5> <input>catch throw(hello).</input> +hello</pre> + <p>If <c>throw/1</c> is not evaluated within a catch, a + <c>nocatch</c> run-time error will occur.</p> + </section> + + <section> + <marker id="try"></marker> + <title>Try</title> + <code type="none"> +try Exprs +catch + [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> + ExceptionBody1; + [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] -> + ExceptionBodyN +end</code> + <p>This is an enhancement of + <seealso marker="#catch">catch</seealso> 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 + <c>try</c> or <c>catch</c> or to default error handling.</p> + <p>Note that although the keyword <c>catch</c> is used in + the <c>try</c> expression, there is not a <c>catch</c> expression + within the <c>try</c> expression.</p> + <p>Returns the value of <c>Exprs</c> (a sequence of expressions + <c>Expr1, ..., ExprN</c>) unless an exception occurs during + the evaluation. In that case the exception is caught and + the patterns <c>ExceptionPattern</c> with the right exception + class <c>Class</c> are sequentially matched against the caught + exception. An omitted <c>Class</c> is shorthand for <c>throw</c>. + If a match succeeds and the optional guard sequence + <c>ExceptionGuardSeq</c> is true, the corresponding + <c>ExceptionBody</c> is evaluated to become the return value.</p> + <p>If an exception occurs during evaluation of <c>Exprs</c> but + there is no matching <c>ExceptionPattern</c> of the right + <c>Class</c> with a true guard sequence, the exception is passed + on as if <c>Exprs</c> had not been enclosed in a <c>try</c> + expression.</p> + <p>If an exception occurs during evaluation of <c>ExceptionBody</c> + it is not caught.</p> + <p>The <c>try</c> expression can have an <c>of</c> + section: + </p> + <code type="none"> +try Exprs of + Pattern1 [when GuardSeq1] -> + Body1; + ...; + PatternN [when GuardSeqN] -> + BodyN +catch + [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> + ExceptionBody1; + ...; + [ClassN:]ExceptionPatternN [when ExceptionGuardSeqN] -> + ExceptionBodyN +end</code> + <p>If the evaluation of <c>Exprs</c> succeeds without an exception, + the patterns <c>Pattern</c> are sequentially matched against + the result in the same way as for a + <seealso marker="#case">case</seealso> expression, except that if + the matching fails, a <c>try_clause</c> run-time error will occur.</p> + <p>An exception occurring during the evaluation of <c>Body</c> is + not caught.</p> + <p>The <c>try</c> expression can also be augmented with an + <c>after</c> section, intended to be used for cleanup with side + effects:</p> + <code type="none"> +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</code> + <p><c>AfterBody</c> is evaluated after either <c>Body</c> or + <c>ExceptionBody</c> no matter which one. The evaluated value of + <c>AfterBody</c> is lost; the return value of the <c>try</c> + expression is the same with an <c>after</c> section as without.</p> + <p>Even if an exception occurs during evaluation of <c>Body</c> or + <c>ExceptionBody</c>, <c>AfterBody</c> is evaluated. In this case + the exception is passed on after <c>AfterBody</c> has been + evaluated, so the exception from the <c>try</c> expression is + the same with an <c>after</c> section as without.</p> + <p>If an exception occurs during evaluation of <c>AfterBody</c> + itself it is not caught, so if <c>AfterBody</c> is evaluated after + an exception in <c>Exprs</c>, <c>Body</c> or <c>ExceptionBody</c>, + that exception is lost and masked by the exception in + <c>AfterBody</c>.</p> + <p>The <c>of</c>, <c>catch</c> and <c>after</c> sections are all + optional, as long as there is at least a <c>catch</c> or an + <c>after</c> section, so the following are valid <c>try</c> + expressions:</p> + <code type="none"> +try Exprs of + Pattern when GuardSeq -> + Body +after + AfterBody +end + +try Exprs +catch + ExpressionPattern -> + ExpressionBody +after + AfterBody +end + +try Exprs after AfterBody end</code> + <p>Example of using <c>after</c>, this code will close the file + even in the event of exceptions in <c>file:read/2</c> or in + <c>binary_to_term/1</c>, and exceptions will be the same as + without the <c>try</c>...<c>after</c>...<c>end</c> expression:</p> + <code type="none"> +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.</code> + <p>Example: Using <c>try</c> to emulate <c>catch Expr</c>.</p> + <code type="none"> +try Expr +catch + throw:Term -> Term; + exit:Reason -> {'EXIT',Reason} + error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}} +end</code> + </section> + + <section> + <title>Parenthesized Expressions</title> + <pre> +(Expr)</pre> + <p>Parenthesized expressions are useful to override + <seealso marker="#prec">operator precedences</seealso>, + for example in arithmetic expressions:</p> + <pre> +1> <input>1 + 2 * 3.</input> +7 +2> <input>(1 + 2) * 3.</input> +9</pre> + </section> + + <section> + <title>Block Expressions</title> + <pre> +begin + Expr1, + ..., + ExprN +end</pre> + <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 <c>ExprN</c>.</p> + </section> + + <section> + <marker id="lcs"></marker> + <title>List Comprehensions</title> + <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 <c>setof</c> and + <c>findall</c> predicates in Prolog.</p> + <p>List comprehensions are written with the following syntax:</p> + <pre> +[Expr || Qualifier1,...,QualifierN]</pre> + <p><c>Expr</c> is an arbitrary expression, and each + <c>Qualifier</c> is either a generator or a filter.</p> + <list type="bulleted"> + <item>A <em>generator</em> is written as: <br></br> + + <c><![CDATA[Pattern <- ListExpr]]></c>. <br></br> +<c>ListExpr</c> must be an expression which evaluates to a + list of terms.</item> +<item>A <em>bit string generator</em> is written as: <br></br> + + <c><![CDATA[BitstringPattern <= BitStringExpr]]></c>. <br></br> +<c>BitStringExpr</c> must be an expression which evaluates to a + bitstring.</item> + <item>A <em>filter</em> is an expression which evaluates to + <c>true</c> or <c>false</c>.</item> + </list> + <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 <c>Expr</c> + for each combination of generator list elements and bit string generator + elements for which all filters are true.</p> <p></p> <p>Example:</p> + <pre> +1> <input>[X*2 || X <- [1,2,3]].</input> +[2,4,6]</pre> + <p>More examples can be found in <em>Programming Examples</em>.</p> + + + </section> + +<section> + <title>Bit String Comprehensions</title> + + <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> + <pre> +<< BitString || Qualifier1,...,QualifierN >></pre> + <p><c>BitString</c> is a bit string expression, and each + <c>Qualifier</c> is either a generator, a bit string generator or a filter.</p> + <list type="bulleted"> + <item>A <em>generator</em> is written as: <br></br> + <c><![CDATA[Pattern <- ListExpr]]></c>. <br></br> + <c>ListExpr</c> must be an expression which evaluates to a + list of terms.</item> + <item>A <em>bit string generator</em> is written as: <br></br> + + <c><![CDATA[BitstringPattern <= BitStringExpr]]></c>. <br></br> +<c>BitStringExpr</c> must be an expression which evaluates to a + bitstring.</item> + <item>A <em>filter</em> is an expression which evaluates to + <c>true</c> or <c>false</c>.</item> + </list> + <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 <c>BitString</c> + for each combination of bit string generator elements for which all + filters are true.</p> + <p></p> + <p>Example:</p> + <pre> +1> <input><< << (X*2) >> || +<<X>> <= << 1,2,3 >> >>.</input> +<<2,4,6>></pre> + <p>More examples can be found in <em>Programming Examples</em>.</p> + </section> + + <section> + <marker id="guards"></marker> + <title>Guard Sequences</title> + + <p>A <em>guard sequence</em> 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></br> +<c>Guard1;...;GuardK</c></p> + <p>A <em>guard</em> is a sequence of guard expressions, separated + by comma (,). The guard is true if all guard expressions + evaluate to <c>true</c>.<br></br> +<c>GuardExpr1,...,GuardExprN</c></p> + <p>The set of valid <em>guard expressions</em> (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> + <list type="bulleted"> + <item>the atom <c>true</c>,</item> + <item>other constants (terms and bound variables), all regarded + as false,</item> + <item>calls to the BIFs specified below,</item> + <item>term comparisons,</item> + <item>arithmetic expressions,</item> + <item>boolean expressions, and</item> + <item>short-circuit expressions (<c>andalso</c>/<c>orelse</c>).</item> + </list> + <table> + <row> + <cell align="left" valign="middle"><c>is_atom/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_binary/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_bitstring/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_float/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_function/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_function/2</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_integer/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_list/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_number/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_pid/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_port/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_record/2</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_record/3</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_reference/1</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>is_tuple/1</c></cell> + </row> + <tcaption>Type Test BIFs.</tcaption> + </table> + <p>Note that most type test BIFs have older equivalents, without + the <c>is_</c> 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> + <row> + <cell align="left" valign="middle"><c>abs(Number)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>bit_size(Bitstring)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>byte_size(Bitstring)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>element(N, Tuple)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>float(Term)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>hd(List)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>length(List)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>node()</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>node(Pid|Ref|Port)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>round(Number)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>self()</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>size(Tuple|Bitstring)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>tl(List)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>trunc(Number)</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>tuple_size(Tuple)</c></cell> + </row> + <tcaption>Other BIFs Allowed in Guard Expressions.</tcaption> + </table> + + <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> + + </section> + + <section> + <marker id="prec"></marker> + <title>Operator Precedence</title> + <p>Operator precedence in falling priority:</p> + <table> + <row> + <cell align="left" valign="middle">:</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">#</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">Unary + - bnot not</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">/ * div rem band and</cell> + <cell align="left" valign="middle">Left associative</cell> + </row> + <row> + <cell align="left" valign="middle">+ - bor bxor bsl bsr or xor</cell> + <cell align="left" valign="middle">Left associative</cell> + </row> + <row> + <cell align="left" valign="middle">++ --</cell> + <cell align="left" valign="middle">Right associative</cell> + </row> + <row> + <cell align="left" valign="middle">== /= =< < >= > =:= =/=</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">andalso</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">orelse</cell> + <cell align="left" valign="middle"> </cell> + </row> + <row> + <cell align="left" valign="middle">= !</cell> + <cell align="left" valign="middle">Right associative</cell> + </row> + <row> + <cell align="left" valign="middle">catch</cell> + <cell align="left" valign="middle"> </cell> + </row> + <tcaption>Operator Precedence.</tcaption> + </table> + <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> + <pre> +<input>6 + 5 * 4 - 3 / 2</input> evaluates to +<input>6 + 20 - 1.5</input> evaluates to +<input>26 - 1.5</input> evaluates to +<input>24.5</input></pre> + </section> +</chapter> + diff --git a/system/doc/reference_manual/functions.xml b/system/doc/reference_manual/functions.xml new file mode 100644 index 0000000000..3746ee6fad --- /dev/null +++ b/system/doc/reference_manual/functions.xml @@ -0,0 +1,168 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Functions</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>functions.xml</file> + </header> + + <section> + <marker id="syntax"></marker> + <title>Function Declaration Syntax</title> + <p>A <em>function declaration</em> is a sequence of function + clauses separated by semicolons, and terminated by period (.).</p> + <p>A <em>function clause</em> consists of a clause head and a + clause body, separated by <c>-></c>.</p> + <p>A clause <em>head</em> consists of the function name, an + argument list, and an optional guard sequence + beginning with the keyword <c>when</c>.</p> + <pre> +Name(Pattern11,...,Pattern1N) [when GuardSeq1] -> + Body1; +...; +Name(PatternK1,...,PatternKN) [when GuardSeqK] -> + BodyK.</pre> + <p>The function name is an atom. Each argument is a pattern.</p> + <p>The number of arguments <c>N</c> is the <em>arity</em> of + the function. A function is uniquely defined by the module name, + function name and arity. That is, two functions with the same + name and in the same module, but with different arities are two + completely different functions.</p> + <p>A function named <c>f</c> in the module <c>m</c> and with arity + <c>N</c> is often denoted as <c>m:f/N</c>.</p> + <p>A clause <em>body</em> consists of a sequence of expressions + separated by comma (,):</p> + <pre> +Expr1, +..., +ExprN</pre> + <p>Valid Erlang expressions and guard sequences are described in + <seealso marker="expressions">Erlang Expressions</seealso>.</p> + <p>Example:</p> + <pre> +fact(N) when N>0 -> % first clause head + N * fact(N-1); % first clause body + +fact(0) -> % second clause head + 1. % second clause body</pre> + </section> + + <section> + <marker id="eval"></marker> + <title>Function Evaluation</title> + <p>When a function <c>m:f/N</c> is called, first the code for + the function is located. If the function cannot be found, an + <c>undef</c> run-time error will occur. Note that the function + must be exported to be visible outside the module it is defined + in.</p> + <p>If the function is found, the function clauses are scanned + sequentially until a clause is found that fulfills the following + two conditions:</p> + <list type="ordered"> + <item>the patterns in the clause head can be successfully + matched against the given arguments, and</item> + <item>the guard sequence, if any, is true.</item> + </list> + <p>If such a clause cannot be found, a <c>function_clause</c> + run-time error will occur.</p> + <p>If such a clause is found, the corresponding clause body is + evaluated. That is, the expressions in the body are evaluated + sequentially and the value of the last expression is returned.</p> + <p>Example: Consider the function <c>fact</c>:</p> + <pre> +-module(m). +-export([fact/1]). + +fact(N) when N>0 -> + N * fact(N-1); +fact(0) -> + 1.</pre> + <p>Assume we want to calculate factorial for 1:</p> + <pre> +1> <input>m:fact(1).</input></pre> + <p>Evaluation starts at the first clause. The pattern <c>N</c> is + matched against the argument 1. The matching succeeds and + the guard (<c>N>0</c>) is true, thus <c>N</c> is bound to 1 and + the corresponding body is evaluated:</p> + <pre> +<input>N * fact(N-1)</input> => (N is bound to 1) +<input>1 * fact(0)</input></pre> + <p>Now <c>fact(0)</c> is called and the function clauses are + scanned sequentially again. First, the pattern <c>N</c> is + matched against 0. The matching succeeds, but the guard + (<c>N>0</c>) is false. Second, the pattern 0 is matched against + 0. The matching succeeds and the body is evaluated:</p> + <pre> +<input>1 * fact(0)</input> => +<input>1 * 1</input> => +<input>1</input></pre> + <p>Evaluation has succeed and <c>m:fact(1)</c> returns 1.</p> + <p>If <c>m:fact/1</c> is called with a negative number as + argument, no clause head will match. A <c>function_clause</c> + run-time error will occur.</p> + </section> + + <section> + <title>Tail recursion</title> + <p>If the last expression of a function body is a function call, + a <em>tail recursive</em> call is done so that no system + resources for example call stack are consumed. This means + that an infinite loop can be done if it uses tail recursive + calls.</p> + <p>Example:</p> + <pre> +loop(N) -> + io:format("~w~n", [N]), + loop(N+1).</pre> + <p>As a counter-example see the factorial example above + that is not tail recursive since a multiplication is done + on the result of the recursive call to <c>fact(N-1)</c>.</p> + </section> + + <section> + <title>Built-In Functions, BIFs</title> + <p><em>Built-in functions</em>, BIFs, are implemented in C code in + the runtime system and do things that are difficult or impossible + to implement in Erlang. Most of the built-in functions belong + to the module <c>erlang</c> but there are also built-in functions + belonging to a few other modules, for example <c>lists</c> and + <c>ets</c>.</p> + <p>The most commonly used BIFs belonging to <c>erlang</c> are + <em>auto-imported</em>, they do not need to be prefixed with + the module name. Which BIFs are auto-imported is specified in + <c>erlang(3)</c>. For example, standard type conversion BIFs like + <c>atom_to_list</c> and BIFs allowed in guards can be called + without specifying the module name. Examples:</p> + <pre> +1> <input>tuple_size({a,b,c}).</input> +3 +2> <input>atom_to_list('Erlang').</input> +"Erlang"</pre> + <p>Note that normally it is the set of auto-imported built-in + functions that is referred to when talking about 'BIFs'.</p> + </section> +</chapter> + diff --git a/system/doc/reference_manual/introduction.xml b/system/doc/reference_manual/introduction.xml new file mode 100644 index 0000000000..3dac5cfe13 --- /dev/null +++ b/system/doc/reference_manual/introduction.xml @@ -0,0 +1,155 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Introduction</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>introduction.xml</file> + </header> + + <section> + <title>Purpose</title> + <p>This reference manual describes the Erlang programming + language. The focus is on the language itself, not + the implementation. The language constructs are described in + text and with examples rather than formally specified, with + the intention to make the manual more readable. + The manual is not intended as a tutorial.</p> + <p>Information about this implementation of Erlang can be found, for + example, in <em>System Principles</em> (starting and stopping, + boot scripts, code loading, error logging, creating target + systems), <em>Efficiency Guide</em> (memory consumption, system + limits) and <em>ERTS User's Guide</em> (crash dumps, drivers).</p> + </section> + + <section> + <title>Prerequisites</title> + <p>It is assumed that the reader has done some programming and + is familiar with concepts such as data types and programming + language syntax.</p> + </section> + + <section> + <title>Document Conventions</title> + <p>In the document, the following terminology is used:</p> + <list type="bulleted"> + <item>A <em>sequence</em> is one or more items. For example, a + clause body consists of a sequence of expressions. This + means that there must be at least one expression.</item> + <item>A <em>list</em> is any number of items. For example, + an argument list can consist of zero, one or more arguments.</item> + </list> + <p>If a feature has been added recently, in Erlang 5.0/OTP R7 or + later, this is mentioned in the text.</p> + </section> + + <section> + <title>Complete List of BIFs</title> + <p>For a complete list of BIFs, their arguments and return values, + refer to <c>erlang(3)</c>.</p> + </section> + + <section> + <title>Reserved Words</title> + <p>The following are reserved words in Erlang:</p> + <p>after and andalso band begin bnot bor bsl bsr bxor case catch + cond div end fun if let not of or orelse query receive rem try + when xor</p> + </section> + + <section> + <title>Character Set</title> + <p>In Erlang 4.8/OTP R5A the syntax of Erlang tokens was extended to + allow the use of the full ISO-8859-1 (Latin-1) character set. This + is noticeable in the following ways:</p> + <list type="bulleted"> + <item> + <p>All the Latin-1 printable characters can be used and are + shown without the escape backslash convention.</p> + </item> + <item> + <p>Atoms and variables can use all Latin-1 letters.</p> + </item> + </list> + <table> + <row> + <cell align="left" valign="middle"><em>Octal</em></cell> + <cell align="left" valign="middle"><em>Decimal</em></cell> + <cell align="left" valign="middle"> </cell> + <cell align="left" valign="middle"><em>Class</em></cell> + </row> + <row> + <cell align="left" valign="middle">200 - 237</cell> + <cell align="left" valign="middle">128 - 159</cell> + <cell align="left" valign="middle"> </cell> + <cell align="left" valign="middle">Control characters</cell> + </row> + <row> + <cell align="left" valign="middle">240 - 277</cell> + <cell align="left" valign="middle">160 - 191</cell> + <cell align="right" valign="middle">- ¿</cell> + <cell align="left" valign="middle">Punctuation characters</cell> + </row> + <row> + <cell align="left" valign="middle">300 - 326</cell> + <cell align="left" valign="middle">192 - 214</cell> + <cell align="center" valign="middle">À - Ö</cell> + <cell align="left" valign="middle">Uppercase letters</cell> + </row> + <row> + <cell align="center" valign="middle">327</cell> + <cell align="center" valign="middle">215</cell> + <cell align="center" valign="middle">×</cell> + <cell align="left" valign="middle">Punctuation character</cell> + </row> + <row> + <cell align="left" valign="middle">330 - 336</cell> + <cell align="left" valign="middle">216 - 222</cell> + <cell align="center" valign="middle">Ø - Þ</cell> + <cell align="left" valign="middle">Uppercase letters</cell> + </row> + <row> + <cell align="left" valign="middle">337 - 366</cell> + <cell align="left" valign="middle">223 - 246</cell> + <cell align="center" valign="middle">ß - ö</cell> + <cell align="left" valign="middle">Lowercase letters</cell> + </row> + <row> + <cell align="center" valign="middle">367</cell> + <cell align="center" valign="middle">247</cell> + <cell align="center" valign="middle">÷</cell> + <cell align="left" valign="middle">Punctuation character</cell> + </row> + <row> + <cell align="left" valign="middle">370 - 377</cell> + <cell align="left" valign="middle">248 - 255</cell> + <cell align="center" valign="middle">ø - ÿ</cell> + <cell align="left" valign="middle">Lowercase letters</cell> + </row> + <tcaption>Character Classes.</tcaption> + </table> + </section> +</chapter> + diff --git a/system/doc/reference_manual/macros.xml b/system/doc/reference_manual/macros.xml new file mode 100644 index 0000000000..a1ba182eff --- /dev/null +++ b/system/doc/reference_manual/macros.xml @@ -0,0 +1,211 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>The Preprocessor</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>macros.xml</file> + </header> + + <section> + <title>File Inclusion</title> + <p>A file can be included in the following way:</p> + <pre> +-include(File). +-include_lib(File).</pre> + <p><c>File</c>, a string, should point out a file. The contents of + this file are included as-is, at the position of the directive.</p> + <p>Include files are typically used for record and macro + definitions that are shared by several modules. It is + recommended that the file name extension <c>.hrl</c> be used + for include files.</p> + <p><c>File</c> may start with a path component <c>$VAR</c>, for + some string <c>VAR</c>. If that is the case, the value of + the environment variable <c>VAR</c> as returned by + <c>os:getenv(VAR)</c> is substituted for <c>$VAR</c>. If + <c>os:getenv(VAR)</c> returns <c>false</c>, <c>$VAR</c> is left + as is.</p> + <p>If the filename <c>File</c> is absolute (possibly after + variable substitution), the include file with that name is + included. Otherwise, the specified file is searched for in + the current working directory, in the same directory as + the module being compiled, and in the directories given by + the <c>include</c> option, in that order. + See <c>erlc(1)</c> and <c>compile(3)</c> for details.</p> + <p>Examples:</p> + <pre> +-include("my_records.hrl"). +-include("incdir/my_records.hrl"). +-include("/home/user/proj/my_records.hrl"). +-include("$PROJ_ROOT/my_records.hrl").</pre> + <p><c>include_lib</c> is similar to <c>include</c>, but should not + point out an absolute file. Instead, the first path component + (possibly after variable substitution) is assumed to be + the name of an application. Example:</p> + <pre> +-include_lib("kernel/include/file.hrl").</pre> + <p>The code server uses <c>code:lib_dir(kernel)</c> to find + the directory of the current (latest) version of Kernel, and + then the subdirectory <c>include</c> is searched for the file + <c>file.hrl</c>.</p> + </section> + + <section> + <title>Defining and Using Macros</title> + <p>A macro is defined the following way:</p> + <code type="none"> +-define(Const, Replacement). +-define(Func(Var1,...,VarN), Replacement).</code> + <p>A macro definition can be placed anywhere among the attributes + and function declarations of a module, but the definition must + come before any usage of the macro.</p> + <p>If a macro is used in several modules, it is recommended that + the macro definition is placed in an include file.</p> + <p>A macro is used the following way:</p> + <code type="none"> +?Const +?Func(Arg1,...,ArgN)</code> + <p>Macros are expanded during compilation. A simple macro + <c>?Const</c> will be replaced with <c>Replacement</c>. + Example:</p> + <code type="none"> +-define(TIMEOUT, 200). +... +call(Request) -> + server:call(refserver, Request, ?TIMEOUT).</code> + <p>This will be expanded to:</p> + <code type="none"> +call(Request) -> + server:call(refserver, Request, 200).</code> + <p>A macro <c>?Func(Arg1,...,ArgN)</c> will be replaced with + <c>Replacement</c>, where all occurrences of a variable <c>Var</c> + from the macro definition are replaced with the corresponding + argument <c>Arg</c>. Example:</p> + <code type="none"> +-define(MACRO1(X, Y), {a, X, b, Y}). +... +bar(X) -> + ?MACRO1(a, b), + ?MACRO1(X, 123)</code> + <p>This will be expanded to:</p> + <code type="none"> +bar(X) -> + {a,a,b,b}, + {a,X,b,123}.</code> + <p>It is good programming practice, but not mandatory, to ensure + that a macro definition is a valid Erlang syntactic form.</p> + <p>To view the result of macro expansion, a module can be compiled + with the <c>'P'</c> option. <c>compile:file(File, ['P'])</c>. + This produces a listing of the parsed code after preprocessing + and parse transforms, in the file <c>File.P</c>.</p> + </section> + + <section> + <title>Predefined Macros</title> + <p>The following macros are predefined:</p> + <taglist> + <tag><c>?MODULE</c></tag> + <item>The name of the current module.</item> + <tag><c>?MODULE_STRING</c>.</tag> + <item>The name of the current module, as a string.</item> + <tag><c>?FILE</c>.</tag> + <item>The file name of the current module.</item> + <tag><c>?LINE</c>.</tag> + <item>The current line number.</item> + <tag><c>?MACHINE</c>.</tag> + <item>The machine name, <c>'BEAM'</c>.</item> + </taglist> + </section> + + <section> + <title>Flow Control in Macros</title> + <p>The following macro directives are supplied:</p> + <taglist> + <tag><c>-undef(Macro).</c></tag> + <item>Causes the macro to behave as if it had never been defined.</item> + <tag><c>-ifdef(Macro).</c></tag> + <item>Evaluate the following lines only if <c>Macro</c> is + defined.</item> + <tag><c>-ifndef(Macro).</c></tag> + <item>Evaluate the following lines only if <c>Macro</c> is not + defined.</item> + <tag><c>-else.</c></tag> + <item>Only allowed after an <c>ifdef</c> or <c>ifndef</c> + directive. If that condition was false, the lines following + <c>else</c> are evaluated instead.</item> + <tag><c>-endif.</c></tag> + <item>Specifies the end of an <c>ifdef</c> or <c>ifndef</c> + directive.</item> + </taglist> + <note> + <p>The macro directives cannot be used inside functions.</p> + </note> + <p>Example:</p> + <code type="none"> +-module(m). +... + +-ifdef(debug). +-define(LOG(X), io:format("{~p,~p}: ~p~n", [?MODULE,?LINE,X])). +-else. +-define(LOG(X), true). +-endif. + +...</code> + <p>When trace output is desired, <c>debug</c> should be defined + when the module <c>m</c> is compiled:</p> + <pre> +% <input>erlc -Ddebug m.erl</input> + +or + +1> <input>c(m, {d, debug}).</input> +{ok,m}</pre> + <p><c>?LOG(Arg)</c> will then expand to a call to <c>io:format/2</c> + and provide the user with some simple trace output.</p> + </section> + + <section> + <title>Stringifying Macro Arguments</title> + <p>The construction <c>??Arg</c>, where <c>Arg</c> is a macro + argument, will be expanded to a string containing the tokens of + the argument. This is similar to the <c>#arg</c> stringifying + construction in C.</p> + <p>The feature was added in Erlang 5.0/OTP R7.</p> + <p>Example:</p> + <code type="none"> +-define(TESTCALL(Call), io:format("Call ~s: ~w~n", [??Call, Call])). + +?TESTCALL(myfunction(1,2)), +?TESTCALL(you:function(2,1)).</code> + <p>results in</p> + <code type="none"> +io:format("Call ~s: ~w~n",["myfunction ( 1 , 2 )",m:myfunction(1,2)]), +io:format("Call ~s: ~w~n",["you : function ( 2 , 1 )",you:function(2,1)]).</code> + <p>That is, a trace output with both the function called and + the resulting value.</p> + </section> +</chapter> + diff --git a/system/doc/reference_manual/make.dep b/system/doc/reference_manual/make.dep new file mode 100644 index 0000000000..0e7687448c --- /dev/null +++ b/system/doc/reference_manual/make.dep @@ -0,0 +1,16 @@ +# ---------------------------------------------------- +# >>>> Do not edit this file <<<< +# This file was automaticly generated by +# /home/otp/bin/docdepend +# ---------------------------------------------------- + + +# ---------------------------------------------------- +# TeX files that the DVI file depend on +# ---------------------------------------------------- + +book.dvi: book.tex code_loading.tex data_types.tex distributed.tex \ + errors.tex expressions.tex functions.tex introduction.tex \ + macros.tex modules.tex part.tex patterns.tex \ + ports.tex processes.tex records.tex + diff --git a/system/doc/reference_manual/modules.xml b/system/doc/reference_manual/modules.xml new file mode 100644 index 0000000000..8b14ca3459 --- /dev/null +++ b/system/doc/reference_manual/modules.xml @@ -0,0 +1,254 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Modules</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>modules.xml</file> + </header> + + <section> + <title>Module Syntax</title> + <p>Erlang code is divided into <em>modules</em>. A module consists + of a sequence of attributes and function declarations, each + terminated by period (.). Example:</p> + <pre> +-module(m). % module attribute +-export([fact/1]). % module attribute + +fact(N) when N>0 -> % beginning of function declaration + N * fact(N-1); % | +fact(0) -> % | + 1. % end of function declaration</pre> + <p>See the <seealso marker="functions">Functions</seealso> chapter + for a description of function declarations.</p> + </section> + + <section> + <title>Module Attributes</title> + <p>A <em>module attribute</em> defines a certain property of a + module. A module attribute consists of a tag and a value.</p> + <pre> +-Tag(Value).</pre> + <p><c>Tag</c> must be an atom, while <c>Value</c> must be a literal + term. As a convenience in user-defined attributes, the literal term + <c>Value</c> the syntax <c>Name/Arity</c> + (where <c>Name</c> is an atom and <c>Arity</c> a positive integer) + will be translated to <c>{Name,Arity}</c>.</p> + + <p>Any module attribute can be specified. The attributes are stored + in the compiled code and can be retrieved by calling + <c>Module:module_info(attributes)</c> or by using + <seealso marker="stdlib:beam_lib#chunks/2">beam_lib(3)</seealso>.</p> + + <p>There are several module attributes with predefined meanings, + some of which have arity two, but user-defined module + attributes must have arity one.</p> + + <section> + <title>Pre-Defined Module Attributes</title> + <p>Pre-defined module attributes should be placed before any + function declaration.</p> + <taglist> + <tag><c>-module(Module).</c></tag> + <item> + <p>Module declaration, defining the name of the module. + The name <c>Module</c>, an atom, should be the same as + the file name minus the extension <c>erl</c>. Otherwise + <seealso marker="code_loading#loading">code loading</seealso> will + not work as intended.</p> + <p>This attribute should be specified first and is the only + attribute which is mandatory.</p> + </item> + <tag><c>-export(Functions).</c></tag> + <item> + <p>Exported functions. Specifies which of the functions + defined within the module that are visible outside + the module.</p> + <p><c>Functions</c> is a list + <c>[Name1/Arity1, ..., NameN/ArityN]</c>, where each + <c>NameI</c> is an atom and <c>ArityI</c> an integer.</p> + </item> + <tag><c>-import(Module,Functions).</c></tag> + <item> + <p>Imported functions. Imported functions can be called + the same way as local functions, that is without any module + prefix.</p> + <p><c>Module</c>, an atom, specifies which module to import + functions from. <c>Functions</c> is a list similar as for + <c>export</c> above.</p> + </item> + <tag><c>-compile(Options).</c></tag> + <item> + <p>Compiler options. <c>Options</c>, which is a single option + or a list of options, will be added to the option list when + compiling the module. See <c>compile(3)</c>.</p> + </item> + <tag><c>-vsn(Vsn).</c></tag> + <item> + <p>Module version. <c>Vsn</c> is any literal term and can be + retrieved using <c>beam_lib:version/1</c>, see + <seealso marker="stdlib:beam_lib#version/1">beam_lib(3)</seealso>.</p> + <p>If this attribute is not specified, the version defaults + to the MD5 checksum of the module.</p> + </item> + </taglist> + </section> + + <section> + <title>Behaviour Module Attribute</title> + <p>It is possible to specify that the module is the callback + module for a <em>behaviour</em>:</p> + <pre> +-behaviour(Behaviour).</pre> + <p>The atom <c>Behaviour</c> gives the name of the behaviour, + which can be a user defined behaviour or one of the OTP + standard behaviours <c>gen_server</c>, <c>gen_fsm</c>, + <c>gen_event</c> or <c>supervisor</c>.</p> + <p>The spelling <c>behavior</c> is also accepted.</p> + <p>Read more about behaviours and callback modules in OTP Design + Principles.</p> + </section> + + <section> + <title>Record Definitions</title> + <p>The same syntax as for module attributes is used by + for record definitions:</p> + <pre> +-record(Record,Fields).</pre> + <p>Record definitions are allowed anywhere in a module, + also among the function declarations. + Read more in <seealso marker="records">Records</seealso>.</p> + </section> + + <section> + <title>The Preprocessor</title> + <p>The same syntax as for module attributes is used by + the preprocessor, which supports file inclusion, macros, + and conditional compilation:</p> + <pre> +-include("SomeFile.hrl"). +-define(Macro,Replacement).</pre> + + <p>Read more in <seealso marker="macros">The Preprocessor</seealso>.</p> + </section> + + <section> + <title>Setting File and Line</title> + <p>The same syntax as for module attributes is used for + changing the pre-defined macros <c>?FILE</c> and <c>?LINE</c>:</p> + <pre> +-file(File, Line).</pre> + <p>This attribute is used by tools such as Yecc to inform the + compiler that the source program was generated by another tool + and indicates the correspondence of source files to lines of + the original user-written file from which the source program + was produced.</p> + </section> + </section> + + <section> + <title>Comments</title> + <p>Comments may be placed anywhere in a module except within strings + and quoted atoms. The comment begins with the character "%", + continues up to, but does not include the next end-of-line, and + has no effect. Note that the terminating end-of-line has + the effect of white space.</p> + </section> + + <section> + <title>The module_info/0 and module_info/1 functions</title> + + <p>The compiler automatically inserts the two special, exported + functions into each module: <c>Module:module_info/0</c> and + <c>Module:module_info/1</c>. These functions can be called to + retrieve information about the module.</p> + + <section> + <title>module_info/0</title> + <p>The <c>module_info/0</c> function in each module returns + a list of <c>{Key,Value}</c> tuples with information about + the module. Currently, the list contain tuples with the following + <c>Key</c>s: <c>attributes</c>, <c>compile</c>, + <c>exports</c>, and <c>imports</c>. The order and number of tuples + may change without prior notice.</p> + + <warning><p>The <c>{imports,Value}</c> tuple may be removed in a future + release because <c>Value</c> is always an empty list. + Do not write code that depends on it being present.</p></warning> + </section> + + <section> + <title>module_info/1</title> + <p>The call <c>module_info(Key)</c>, where key is an atom, + returns a single piece of information about the module.</p> + + <p>The following values are allowed for <c>Key</c>:</p> + + <taglist> + <tag><c>attributes</c></tag> + <item> + <p>Return a list of <c>{AttributeName,ValueList}</c> tuples, + where <c>AttributeName</c> is the name of an attribute, + and <c>ValueList</c> is a list of values. Note: a given + attribute may occur more than once in the list with different + values if the attribute occurs more than once in the module.</p> + + <p>The list of attributes will be empty if + the module has been stripped with + <seealso marker="stdlib:beam_lib#strip/1">beam_lib(3)</seealso>.</p> + </item> + + <tag><c>compile</c></tag> + <item> + <p>Return a list of tuples containing information about + how the module was compiled. This list will be empty if + the module has been stripped with + <seealso marker="stdlib:beam_lib#strip/1">beam_lib(3)</seealso>.</p> + </item> + + <tag><c>imports</c></tag> + <item> + <p>Always return an empty list. The <c>imports</c> key may not + be supported in future release.</p> + </item> + + <tag><c>exports</c></tag> + <item> + <p>Return a list of <c>{Name,Arity}</c> tuples with + all exported functions in the module.</p> + </item> + + <tag><c>functions</c></tag> + <item> + <p>Return a list of <c>{Name,Arity}</c> tuples with + all functions in the module.</p> + </item> + </taglist> + </section> + </section> + +</chapter> + diff --git a/system/doc/reference_manual/part.xml b/system/doc/reference_manual/part.xml new file mode 100644 index 0000000000..aebeaf335a --- /dev/null +++ b/system/doc/reference_manual/part.xml @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE part SYSTEM "part.dtd"> + +<part xmlns:xi="http://www.w3.org/2001/XInclude"> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Erlang Reference Manual</title> + <prepared>Gunilla Arendt</prepared> + <docno></docno> + <date>2003-01-11</date> + <rev></rev> + </header> + <xi:include href="introduction.xml"/> + <xi:include href="data_types.xml"/> + <xi:include href="patterns.xml"/> + <xi:include href="modules.xml"/> + <xi:include href="functions.xml"/> + <xi:include href="expressions.xml"/> + <xi:include href="macros.xml"/> + <xi:include href="records.xml"/> + <xi:include href="errors.xml"/> + <xi:include href="processes.xml"/> + <xi:include href="distributed.xml"/> + <xi:include href="code_loading.xml"/> + <xi:include href="ports.xml"/> +</part> + diff --git a/system/doc/reference_manual/patterns.xml b/system/doc/reference_manual/patterns.xml new file mode 100644 index 0000000000..7289f14d73 --- /dev/null +++ b/system/doc/reference_manual/patterns.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Pattern Matching</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>patterns.xml</file> + </header> + + <section> + <title>Pattern Matching</title> + <p>Variables are bound to values through the <em>pattern matching</em> mechanism. Pattern matching occurs when + evaluating a function call, <c>case</c>- <c>receive</c>- + <c>try</c>- expressions and match operator (=) expressions.</p> + <p>In a pattern matching, a left-hand side + <seealso marker="expressions#pattern">pattern</seealso> is matched + against a right-hand side + <seealso marker="expressions#term">term</seealso>. If + the matching succeeds, any unbound variables in the pattern + become bound. If the matching fails, a run-time error occurs.</p> + <p>Examples:</p> + <pre> +1> <input>X.</input> +** 1: variable 'X' is unbound ** +2> <input>X = 2.</input> +2 +3> <input>X + 1.</input> +3 +4> <input>{X, Y} = {1, 2}.</input> +** exception error: no match of right hand side value {1,2} +5> <input>{X, Y} = {2, 3}.</input> +{2,3} +6> <input>Y.</input> +3</pre> + </section> +</chapter> + diff --git a/system/doc/reference_manual/ports.xml b/system/doc/reference_manual/ports.xml new file mode 100644 index 0000000000..4847dd67cd --- /dev/null +++ b/system/doc/reference_manual/ports.xml @@ -0,0 +1,159 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2004</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Ports and Port Drivers</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>ports.xml</file> + </header> + <p>Examples of how to use ports and port drivers can be found in + <em>Interoperability Tutorial</em>. The BIFs mentioned are as usual + documented in <c>erlang(3)</c>.</p> + + <section> + <title>Ports</title> + <p><em>Ports</em> provide the basic mechanism for communication + with the external world, from Erlang's point of view. They + provide a byte-oriented interface to an external program. When a + port has been created, Erlang can communicate with it by sending + and receiving lists of bytes, including binaries.</p> + <p>The Erlang process which creates a port is said to be + the <em>port owner</em>, or the <em>connected process</em> of + the port. All communication to and from the port should go via + the port owner. If the port owner terminates, so will the port + (and the external program, if it is written correctly).</p> + <p>The external program resides in another OS process. By default, + it should read from standard input (file descriptor 0) and write + to standard output (file descriptor 1). The external program + should terminate when the port is closed.</p> + </section> + + <section> + <title>Port Drivers</title> + <p>It is also possible to write a driver in C according to certain + principles and dynamically link it to the Erlang runtime system. + The linked-in driver looks like a port from the Erlang + programmer's point of view and is called a <em>port driver</em>.</p> + <warning> + <p>An erroneous port driver will cause the entire Erlang runtime + system to leak memory, hang or crash.</p> + </warning> + <p>Port drivers are documented in <c>erl_driver(4)</c>, + <c>driver_entry(1)</c> and <c>erl_ddll(3)</c>.</p> + </section> + + <section> + <title>Port BIFs</title> + <p>To create a port:</p> + <table> + <row> + <cell align="left" valign="middle"><c>open_port(PortName, PortSettings</c></cell> + <cell align="left" valign="middle">Returns a port identifier <c>Port</c>as the result of opening a new Erlang port. Messages can be sent to and received from a port identifier, just like a pid. Port identifiers can also be linked to or registered under a name using <c>link/1</c>and <c>register/2</c>.</cell> + </row> + <tcaption>Port Creation BIF.</tcaption> + </table> + <p><c>PortName</c> is usually a tuple <c>{spawn,Command}</c>, where + the string <c>Command</c> is the name of the external program. + The external program runs outside the Erlang workspace unless a + port driver with the name <c>Command</c> is found. If found, that + driver is started.</p> + <p><c>PortSettings</c> is a list of settings (options) for the port. + The list typically contains at least a tuple <c>{packet,N}</c> + which specifies that data sent between the port and the external + program are preceded by an N-byte length indicator. Valid values + for N are 1, 2 or 4. If binaries should be used instead of lists + of bytes, the option <c>binary</c> must be included.</p> + <p>The port owner <c>Pid</c> can communicate with the port + <c>Port</c> by sending and receiving messages. (In fact, any + process can send the messages to the port, but the messages from + the port always go to the port owner).</p> + <p>Below, <c>Data</c> must be an I/O list. An I/O list is a binary + or a (possibly deep) list of binaries or integers in the range + 0..255.</p> + <table> + <row> + <cell align="left" valign="middle"><c>{Pid,{command,Data}}</c></cell> + <cell align="left" valign="middle">Sends <c>Data</c>to the port.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{Pid,close}</c></cell> + <cell align="left" valign="middle">Closes the port. Unless the port is already closed, the port replies with <c>{Port,closed}</c>when all buffers have been flushed and the port really closes.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{Pid,{connect,NewPid}}</c></cell> + <cell align="left" valign="middle">Sets the port owner of <c>Port</c>to <c>NewPid</c>. Unless the port is already closed, the port replies with<c>{Port,connected}</c>to the old port owner. Note that the old port owner is still linked to the port, but the new port owner is not.</cell> + </row> + <tcaption>Messages Sent To a Port.</tcaption> + </table> + <table> + <row> + <cell align="left" valign="middle"><c>{Port,{data,Data}}</c></cell> + <cell align="left" valign="middle"><c>Data</c>is received from the external program.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{Port,closed}</c></cell> + <cell align="left" valign="middle">Reply to <c>Port ! {Pid,close}</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>{Port,connected}</c></cell> + <cell align="left" valign="middle">Reply to <c>Port ! {Pid,{connect,NewPid}}</c></cell> + </row> + <row> + <cell align="left" valign="middle"><c>{'EXIT',Port,Reason}</c></cell> + <cell align="left" valign="middle">If the port has terminated for some reason.</cell> + </row> + <tcaption>Messages Received From a Port.</tcaption> + </table> + <p>Instead of sending and receiving messages, there are also a + number of BIFs that can be used. These can be called by any + process, not only the port owner.</p> + <table> + <row> + <cell align="left" valign="middle"><c>port_command(Port,Data)</c></cell> + <cell align="left" valign="middle">Sends <c>Data</c>to the port.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>port_close(Port)</c></cell> + <cell align="left" valign="middle">Closes the port.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>port_connect(Port,NewPid)</c></cell> + <cell align="left" valign="middle">Sets the port owner of <c>Port</c>to <c>NewPid</c>. The old port owner <c>Pid</c>stays linked to the port and have to call <c>unlink(Port)</c>if this is not desired.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>erlang:port_info(Port,Item)</c></cell> + <cell align="left" valign="middle">Returns information as specified by <c>Item</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>erlang:ports()</c></cell> + <cell align="left" valign="middle">Returns a list of all ports on the current node.</cell> + </row> + <tcaption>Port BIFs.</tcaption> + </table> + <p>There are some additional BIFs that only apply to port drivers: + <c>port_control/3</c> and <c>erlang:port_call/3</c>.</p> + </section> +</chapter> + diff --git a/system/doc/reference_manual/processes.xml b/system/doc/reference_manual/processes.xml new file mode 100644 index 0000000000..305d7d9c66 --- /dev/null +++ b/system/doc/reference_manual/processes.xml @@ -0,0 +1,205 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Processes</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>processes.xml</file> + </header> + + <section> + <title>Processes</title> + <p>Erlang is designed for massive concurrency. Erlang processes are + light-weight (grow and shrink dynamically) with small memory + footprint, fast to create and terminate and the scheduling + overhead is low.</p> + </section> + + <section> + <title>Process Creation</title> + <p>A process is created by calling <c>spawn</c>:</p> + <pre> +spawn(Module, Name, Args) -> pid() + Module = Name = atom() + Args = [Arg1,...,ArgN] + ArgI = term()</pre> + <p><c>spawn</c> creates a new process and returns the pid.</p> + <p>The new process will start executing in + <c>Module:Name(Arg1,...,ArgN)</c> where the arguments is + the elements of the (possible empty) <c>Args</c> argument list.</p> + <p>There exist a number of other <c>spawn</c> BIFs, for example + <c>spawn/4</c> for spawning a process at another node.</p> + </section> + + <section> + <title>Registered Processes</title> + <p>Besides addressing a process by using its pid, there are also + BIFs for registering a process under a name. The name must be an + atom and is automatically unregistered if the process terminates:</p> + <table> + <row> + <cell align="left" valign="middle"><c>register(Name, Pid)</c></cell> + <cell align="left" valign="middle">Associates the name <c>Name</c>, an atom, with the process <c>Pid</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>registered()</c></cell> + <cell align="left" valign="middle">Returns a list of names which have been registered using<c>register/2</c>.</cell> + </row> + <row> + <cell align="left" valign="middle"><c>whereis(Name)</c></cell> + <cell align="left" valign="middle">Returns the pid registered under <c>Name</c>, or<c>undefined</c>if the name is not registered.</cell> + </row> + <tcaption>Name Registration BIFs.</tcaption> + </table> + </section> + + <section> + <marker id="term"></marker> + <title>Process Termination</title> + <p>When a process terminates, it always terminates with an + <em>exit reason</em>. The reason may be any term.</p> + <p>A process is said to terminate <em>normally</em>, if the exit + reason is the atom <c>normal</c>. A process with no more code to + execute terminates normally.</p> + <p>A process terminates with exit reason <c>{Reason,Stack}</c> + when a run-time error occurs. See + <seealso marker="errors#exit_reasons">Error and Error Handling</seealso>.</p> + <p>A process can terminate itself by calling one of the BIFs + <c>exit(Reason)</c>, + <c>erlang:error(Reason)</c>, <c>erlang:error(Reason, Args)</c>, + <c>erlang:fault(Reason)</c> or <c>erlang:fault(Reason, Args)</c>. + The process then terminates with reason <c>Reason</c> for + <c>exit/1</c> or <c>{Reason,Stack} for the others</c>.</p> + <p>A process may also be terminated if it receives an exit signal + with another exit reason than <c>normal</c>, see + <seealso marker="#errors">Error Handling</seealso> below.</p> + </section> + + <section> + <title>Message Sending</title> + <p>Processes communicate by sending and receiving messages. + Messages are sent by using + the <seealso marker="expressions#send">send operator !</seealso> + and received by calling + <seealso marker="expressions#receive">receive</seealso>.</p> + <p>Message sending is asynchronous and safe, the message is + guaranteed to eventually reach the recipient, provided that + the recipient exists.</p> + </section> + + <section> + <title>Links</title> + <p>Two processes can be <em>linked</em> to each other. A link + between two processes <c>Pid1</c> and <c>Pid2</c> is created + by <c>Pid1</c> calling the BIF <c>link(Pid2)</c> (or vice versa). + There also exists a number a <c>spawn_link</c> BIFs, which spawns + and links to a process in one operation.</p> + <p>Links are bidirectional and there can only be one link between + two processes. Repeated calls to <c>link(Pid)</c> have no effect.</p> + <p>A link can be removed by calling the BIF <c>unlink(Pid)</c>.</p> + <p>Links are used to monitor the behaviour of other processes, see + <seealso marker="#errors">Error Handling</seealso> below.</p> + </section> + + <section> + <marker id="errors"></marker> + <title>Error Handling</title> + <p>Erlang has a built-in feature for error handling between + processes. Terminating processes will emit exit signals to all + linked processes, which may terminate as well or handle the exit + in some way. This feature can be used to build hierarchical + program structures where some processes are supervising other + processes, for example restarting them if they terminate + abnormally.</p> + <p>Refer to OTP Design Principles for more information about + OTP supervision trees, which uses this feature.</p> + + <section> + <title>Emitting Exit Signals</title> + <p>When a process terminates, it will terminate with an <em>exit reason</em> as explained in <seealso marker="#term">Process Termination</seealso> above. This exit reason is emitted in + an <em>exit signal</em> to all linked processes.</p> + <p>A process can also call the function <c>exit(Pid,Reason)</c>. + This will result in an exit signal with exit reason + <c>Reason</c> being emitted to <c>Pid</c>, but does not affect + the calling process.</p> + </section> + + <section> + <title>Receiving Exit Signals</title> + <p>The default behaviour when a process receives an exit signal + with an exit reason other than <c>normal</c>, is to terminate + and in turn emit exit signals with the same exit reason to its + linked processes. An exit signal with reason <c>normal</c> is + ignored.</p> + <p>A process can be set to trap exit signals by calling:</p> + <pre> +process_flag(trap_exit, true)</pre> + <p>When a process is trapping exits, it will not terminate when + an exit signal is received. Instead, the signal is transformed + into a message <c>{'EXIT',FromPid,Reason}</c> which is put into + the mailbox of the process just like a regular message.</p> + <p>An exception to the above is if the exit reason is <c>kill</c>, + that is if <c>exit(Pid,kill)</c> has been called. This will + unconditionally terminate the process, regardless of if it is + trapping exit signals or not.</p> + </section> + </section> + + <section> + <title>Monitors</title> + <p>An alternative to links are <em>monitors</em>. A process + <c>Pid1</c> can create a monitor for <c>Pid2</c> by calling + the BIF <c>erlang:monitor(process, Pid2)</c>. The function returns + a reference <c>Ref</c>.</p> + <p>If <c>Pid2</c> terminates with exit reason <c>Reason</c>, a + 'DOWN' message is sent to <c>Pid1</c>:</p> + <code type="none"> +{'DOWN', Ref, process, Pid2, Reason}</code> + <p>If <c>Pid2</c> does not exist, the 'DOWN' message is sent + immediately with <c>Reason</c> set to <c>noproc</c>.</p> + <p>Monitors are unidirectional. Repeated calls to + <c>erlang:monitor(process, Pid)</c> will create several, + independent monitors and each one will send a 'DOWN' message when + <c>Pid</c> terminates.</p> + <p>A monitor can be removed by calling + <c>erlang:demonitor(Ref)</c>.</p> + <p>It is possible to create monitors for processes with registered + names, also at other nodes.</p> + </section> + + <section> + <title>Process Dictionary</title> + <p>Each process has its own process dictionary, accessed by calling + the following BIFs:</p> + <pre> +put(Key, Value) +get(Key) +get() +get_keys(Value) +erase(Key) +erase()</pre> + </section> +</chapter> + diff --git a/system/doc/reference_manual/records.xml b/system/doc/reference_manual/records.xml new file mode 100644 index 0000000000..e2fe5fe8de --- /dev/null +++ b/system/doc/reference_manual/records.xml @@ -0,0 +1,169 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE chapter SYSTEM "chapter.dtd"> + +<chapter> + <header> + <copyright> + <year>2003</year><year>2009</year> + <holder>Ericsson AB. All Rights Reserved.</holder> + </copyright> + <legalnotice> + The contents of this file are subject to the Erlang Public License, + Version 1.1, (the "License"); you may not use this file except in + compliance with the License. You should have received a copy of the + Erlang Public License along with this software. If not, it can be + retrieved online at http://www.erlang.org/. + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See + the License for the specific language governing rights and limitations + under the License. + + </legalnotice> + + <title>Records</title> + <prepared></prepared> + <docno></docno> + <date></date> + <rev></rev> + <file>records.xml</file> + </header> + <p>A record is a data structure for storing a fixed number of + elements. It has named fields and is similar to a struct in C. + Record expressions are translated to tuple expressions during + compilation. Therefore, record expressions are not understood by + the shell unless special actions are taken. See <c>shell(3)</c> + for details.</p> + <p>More record examples can be found in <em>Programming Examples</em>.</p> + + <section> + <title>Defining Records</title> + <p>A record definition consists of the name of the record, + followed by the field names of the record. Record and field names + must be atoms. Each field can be given an optional default value. + If no default value is supplied, <c>undefined</c> will be used.</p> + <pre> +-record(Name, {Field1 [= Value1], + ... + FieldN [= ValueN]}).</pre> + <p>A record definition can be placed anywhere among the attributes + and function declarations of a module, but the definition must + come before any usage of the record.</p> + <p>If a record is used in several modules, it is recommended that + the record definition is placed in an include file.</p> + </section> + + <section> + <title>Creating Records</title> + <p>The following expression creates a new <c>Name</c> record where + the value of each field <c>FieldI</c> is the value of evaluating + the corresponding expression <c>ExprI</c>:</p> + <pre> +#Name{Field1=Expr1,...,FieldK=ExprK}</pre> + <p>The fields may be in any order, not necessarily the same order as + in the record definition, and fields can be omitted. Omitted + fields will get their respective default value instead.</p> + <p>If several fields should be assigned the same value, + the following construction can be used:</p> + <pre> +#Name{Field1=Expr1,...,FieldK=ExprK, _=ExprL}</pre> + <p>Omitted fields will then get the value of evaluating <c>ExprL</c> + instead of their default values. This feature was added in + Erlang 5.1/OTP R8 and is primarily intended to be used to create + patterns for ETS and Mnesia match functions. Example:</p> + <pre> +-record(person, {name, phone, address}). + +... + +lookup(Name, Tab) -> + ets:match_object(Tab, #person{name=Name, _='_'}).</pre> + </section> + + <section> + <title>Accessing Record Fields</title> + <pre> +Expr#Name.Field</pre> + <p>Returns the value of the specified field. <c>Expr</c> should + evaluate to a <c>Name</c> record.</p> + <p>The following expression returns the position of the specified + field in the tuple representation of the record:</p> + <pre> +#Name.Field</pre> + <p>Example:</p> + <pre> +-record(person, {name, phone, address}). + +... + +lookup(Name, List) -> + lists:keysearch(Name, #person.name, List).</pre> + </section> + + <section> + <title>Updating Records</title> + <pre> +Expr#Name{Field1=Expr1,...,FieldK=ExprK}</pre> + <p><c>Expr</c> should evaluate to a <c>Name</c> record. Returns a + copy of this record, with the value of each specified field + <c>FieldI</c> changed to the value of evaluating the corresponding + expression <c>ExprI</c>. All other fields retain their old + values.</p> + <p></p> + </section> + + <section> + <title>Records in Guards</title> + <p>Since record expressions are expanded to tuple expressions, + creating records and accessing record fields are allowed in + guards. However all subexpressions, for example for field + initiations, must of course be valid guard expressions as well. + Examples:</p> + <code type="none"> +handle(Msg, State) when Msg==#msg{to=void, no=3} -> + ... + +handle(Msg, State) when State#state.running==true -> + ...</code> + <p>There is also a type test BIF <c>is_record(Term, RecordTag)</c>. + Example:</p> + <pre> +is_person(P) when is_record(P, person) -> + true; +is_person(_P) -> + false.</pre> + </section> + + <section> + <title>Records in Patterns</title> + <p>A pattern that will match a certain record is created the same + way as a record is created:</p> + <pre> +#Name{Field1=Expr1,...,FieldK=ExprK}</pre> + <p>In this case, one or more of <c>Expr1</c>...<c>ExprK</c> may be + unbound variables.</p> + </section> + + <section> + <title>Internal Representation of Records</title> + <p>Record expressions are translated to tuple expressions during + compilation. A record defined as</p> + <pre> +-record(Name, {Field1,...,FieldN}).</pre> + <p>is internally represented by the tuple</p> + <pre> +{Name,Value1,...,ValueN}</pre> + <p>where each <c>ValueI</c> is the default value for <c>FieldI</c>.</p> + <p>To each module using records, a pseudo function is added + during compilation to obtain information about records:</p> + <pre> +record_info(fields, Record) -> [Field] +record_info(size, Record) -> Size</pre> + <p><c>Size</c> is the size of the tuple representation, that is + one more than the number of fields.</p> + <p>In addition, <c>#Record.Name</c> returns the index in the tuple + representation of <c>Name</c> of the record <c>Record</c>. + <c>Name</c> must be an atom.</p> + </section> +</chapter> + diff --git a/system/doc/reference_manual/xmlfiles.mk b/system/doc/reference_manual/xmlfiles.mk new file mode 100644 index 0000000000..6886c8c7cf --- /dev/null +++ b/system/doc/reference_manual/xmlfiles.mk @@ -0,0 +1,33 @@ +# +# %CopyrightBegin% +# +# Copyright Ericsson AB 2009. All Rights Reserved. +# +# The contents of this file are subject to the Erlang Public License, +# Version 1.1, (the "License"); you may not use this file except in +# compliance with the License. You should have received a copy of the +# Erlang Public License along with this software. If not, it can be +# retrieved online at http://www.erlang.org/. +# +# Software distributed under the License is distributed on an "AS IS" +# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See +# the License for the specific language governing rights and limitations +# under the License. +# +# %CopyrightEnd% +# +REF_MAN_CHAPTER_FILES = \ + introduction.xml \ + data_types.xml \ + patterns.xml \ + modules.xml \ + functions.xml \ + expressions.xml \ + macros.xml \ + records.xml \ + errors.xml \ + processes.xml \ + distributed.xml \ + code_loading.xml \ + ports.xml + |