Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 67

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../otp_doc.css" type="text/css">
<title>Erlang -- Sequential Programming</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Getting Started with Erlang</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../js/flipmenu">
<li id="no" title="Introduction" expanded="false">Introduction<ul>
<li><a href="intro.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="intro.html#id62060">Introduction</a></li>
<li title="Things Left Out"><a href="intro.html#id60748">Things Left Out</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Sequential Programming" expanded="true">Sequential Programming<ul>
<li><a href="seq_prog.html">
              Top of chapter
            </a></li>
<li title="The Erlang Shell"><a href="seq_prog.html#id62023">The Erlang Shell</a></li>
<li title="Modules and Functions"><a href="seq_prog.html#id57046">Modules and Functions</a></li>
<li title="Atoms"><a href="seq_prog.html#id57421">Atoms</a></li>
<li title="Tuples"><a href="seq_prog.html#id62855">Tuples</a></li>
<li title="Lists"><a href="seq_prog.html#id57425">Lists</a></li>
<li title="Standard Modules and Manual Pages"><a href="seq_prog.html#id63464">Standard Modules and Manual Pages</a></li>
<li title="Writing Output to a Terminal"><a href="seq_prog.html#id63511">Writing Output to a Terminal</a></li>
<li title="A Larger Example"><a href="seq_prog.html#id65303">A Larger Example</a></li>
<li title="Matching, Guards and Scope of Variables"><a href="seq_prog.html#id63164">Matching, Guards and Scope of Variables</a></li>
<li title="More About Lists"><a href="seq_prog.html#id63431">More About Lists</a></li>
<li title="If and Case"><a href="seq_prog.html#id66137">If and Case</a></li>
<li title="Built In Functions (BIFs)"><a href="seq_prog.html#id66368">Built In Functions (BIFs)</a></li>
<li title="Higher Order Functions (Funs)"><a href="seq_prog.html#id66559">Higher Order Functions (Funs)</a></li>
</ul>
</li>
<li id="no" title="Concurrent Programming" expanded="false">Concurrent Programming<ul>
<li><a href="conc_prog.html">
              Top of chapter
            </a></li>
<li title="Processes"><a href="conc_prog.html#id66869">Processes</a></li>
<li title="Message Passing"><a href="conc_prog.html#id67007">Message Passing</a></li>
<li title="Registered Process Names"><a href="conc_prog.html#id67348">Registered Process Names</a></li>
<li title="Distributed Programming"><a href="conc_prog.html#id67451">Distributed Programming</a></li>
<li title="A Larger Example"><a href="conc_prog.html#id67712">A Larger Example</a></li>
</ul>
</li>
<li id="no" title="Robustness" expanded="false">Robustness<ul>
<li><a href="robustness.html">
              Top of chapter
            </a></li>
<li title="Timeouts"><a href="robustness.html#id68419">Timeouts</a></li>
<li title="Error Handling"><a href="robustness.html#id68545">Error Handling</a></li>
<li title="The Larger Example with Robustness Added"><a href="robustness.html#id68732">The Larger Example with Robustness Added</a></li>
</ul>
</li>
<li id="no" title="Records and Macros" expanded="false">Records and Macros<ul>
<li><a href="record_macros.html">
              Top of chapter
            </a></li>
<li title="The Larger Example Divided into Several Files"><a href="record_macros.html#id68928">The Larger Example Divided into Several Files</a></li>
<li title="Header Files"><a href="record_macros.html#id69078">Header Files</a></li>
<li title="Records"><a href="record_macros.html#id69123">Records</a></li>
<li title="Macros"><a href="record_macros.html#id69217">Macros</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>2 Sequential Programming</h1>
  

  <h3><a name="id62023">2.1 
        The Erlang Shell</a></h3>
    
    <p>Most operating systems have a command interpreter or shell, Unix
      and Linux have many, Windows has the Command Prompt. Erlang has
      its own shell where you can directly write bits of Erlang code
      and evaluate (run) them to see what happens (see
      <span class="bold_code"><a href="javascript:erlhref('../../','stdlib','shell.html');">shell(3)</a></span>). Start
      the Erlang shell (in Linux or UNIX) by starting a shell or
      command interpreter in your operating system and typing
      <span class="code">erl</span>, you will see something like this.</p>
    <div class="example"><pre>
% <span class="bold_code">erl</span>
Erlang R15B (erts-5.9.1) [source] [smp:8:8] [rq:8] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
1&gt;</pre></div>
    <p>Now type in "2 + 5." as shown below.</p>
    <div class="example"><pre>
1&gt; <span class="bold_code">2 + 5.</span>
7
2&gt;</pre></div>
    <p>In Windows, the shell is started by double-clicking on the Erlang
      shell icon.</p>
    <p>You'll notice that the Erlang shell has numbered the lines that
      can be entered, (as 1&gt; 2&gt;) and that it has correctly told you
      that 2 + 5 is 7! Also notice that you have to tell it you are
      done entering code by finishing with a full stop "." and a
      carriage return. If you make mistakes writing things in the shell,
      you can delete things by using the backspace key as in most
      shells. There are many more editing commands in the shell
      (See the chapter <span class="bold_code"><a href="javascript:erlhref('../../','erts','tty.html');">"tty - A command line interface"</a></span> in ERTS User's Guide).</p>
    <p>(Note: you will find a lot of line numbers given by the shell
      out of sequence in this tutorial as it was written and the code
      tested in several sessions).</p>
    <p>Now let's try a more complex calculation.</p>
    <div class="example"><pre>
2&gt; <span class="bold_code">(42 + 77) * 66 / 3.</span>
2618.0</pre></div>
    <p>Here you can see the use of brackets and the multiplication
      operator "*" and division operator "/", just as in normal
      arithmetic (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','expressions.html');">"Arithmetic Expressions"</a></span> in the Erlang Reference Manual).</p>
    <p>To shutdown the Erlang system and the Erlang shell type
      Control-C. You will see the following output:</p>
    <div class="example"><pre>
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution
<span class="bold_code">a</span>
%</pre></div>
    <p>Type "a" to leave the Erlang system.</p>
    <p>Another way to shutdown the Erlang system is by entering
      <span class="code">halt()</span>:</p>
    <div class="example"><pre>
3&gt; <span class="bold_code">halt().</span>
% </pre></div>
  

  <h3><a name="id57046">2.2 
        Modules and Functions</a></h3>
    
    <p>A programming language isn't much use if you can just run code
      from the shell. So here is a small Erlang program. Enter it into
      a file called <span class="code">tut.erl</span> (the file name <span class="code">tut.erl</span> is
      important, also make sure that it is in the same directory as
      the one where you started <span class="code">erl</span>) using a suitable
      text editor. If you are lucky your editor will have an Erlang
      mode which will make it easier for you to enter and format your
      code nicely (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','tools','erlang_mode_chapter.html');">"The Erlang mode for Emacs"</a></span> in Tools User's Guide), but you can manage
      perfectly well without. Here's the code to enter:</p>
    <div class="example"><pre>
-module(tut).
-export([double/1]).

double(X) -&gt;
    2 * X.</pre></div>
    <p>It's not hard to guess that this "program" doubles the value of
      numbers. I'll get back to the first two lines later. Let's compile
      the program. This can be done in your Erlang shell as shown below:</p>
    <div class="example"><pre>
3&gt; <span class="bold_code">c(tut).</span>
{ok,tut}</pre></div>
    <p>The <span class="code">{ok,tut}</span> tells you that the compilation was OK. If it
      said "error" instead, you have made some mistake in the text you
      entered and there will also be error messages to give you some
      idea as to what has gone wrong so you can change what you have
      written and try again.</p>
    <p>Now lets run the program.</p>
    <div class="example"><pre>
4&gt; <span class="bold_code">tut:double(10).</span>
20</pre></div>
    <p>As expected double of 10 is 20.</p>
    <p>Now let's get back to the first two lines. Erlang programs are
      written in files. Each file contains what we call an Erlang
      <strong>module</strong>. The first line of code in the module tells us
      the name of the module (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','modules.html');">"Modules"</a></span>
      in the Erlang Reference Manual).</p>
    <div class="example"><pre>
-module(tut).</pre></div>
    <p>This tells us that the module is called <strong>tut</strong>. Note
      the "." at the end of the line. The files which are used to store
      the module must have the same name as the module but with
      the extension ".erl". In our case the file name is <span class="code">tut.erl</span>.
      When we use a function in another module, we use the syntax,
      <span class="code">module_name:function_name(arguments)</span>. So</p>
    <div class="example"><pre>
4&gt; <span class="bold_code">tut:double(10).</span></pre></div>
    <p>means call function <span class="code">double</span> in module <span class="code">tut</span> with
      argument "10".</p>
    <p>The second line:</p>
    <div class="example"><pre>
-export([double/1]).</pre></div>
    <p>says that the module <span class="code">tut</span> contains a function called
      <span class="code">double</span> which takes one argument (<span class="code">X</span> in our example)
      and that this function can be called from outside the module
      <span class="code">tut</span>. More about this later. Again note the "." at the end
      of the line.</p>
    <p>Now for a more complicated example, the factorial of a number
      (e.g. factorial of 4 is 4 * 3 * 2 * 1). Enter the following code
      in a file called <span class="code">tut1.erl</span>.</p>
    <div class="example"><pre>
-module(tut1).
-export([fac/1]).

fac(1) -&gt;
    1;
fac(N) -&gt;
    N * fac(N - 1).</pre></div>
    <p>Compile the file</p>
    <div class="example"><pre>
5&gt; <span class="bold_code">c(tut1).</span>
{ok,tut1}</pre></div>
    <p>And now calculate the factorial of 4.</p>
    <div class="example"><pre>
6&gt; <span class="bold_code">tut1:fac(4).</span>
24</pre></div>
    <p>The first part:</p>
    <div class="example"><pre>
fac(1) -&gt;
    1;</pre></div>
    <p>says that the factorial of 1 is 1. Note that we end this part
      with a ";" which indicates that there is more of this function to
      come. The second part:</p>
    <div class="example"><pre>
fac(N) -&gt;
    N * fac(N - 1).</pre></div>
    <p>says that the factorial of N is N multiplied by the factorial of
      N - 1. Note that this part ends with a "." saying that there are
      no more parts of this function.</p>
    <p>A function can have many arguments. Let's expand the module
      <span class="code">tut1</span> with the rather stupid function to multiply two
      numbers:</p>
    <div class="example"><pre>
-module(tut1).
-export([fac/1, mult/2]).

fac(1) -&gt;
    1;
fac(N) -&gt;
    N * fac(N - 1).

mult(X, Y) -&gt;
    X * Y.</pre></div>
    <p>Note that we have also had to expand the <span class="code">-export</span> line
      with the information that there is another function <span class="code">mult</span>
      with two arguments.</p>
    <p>Compile:</p>
    <div class="example"><pre>
7&gt; <span class="bold_code">c(tut1).</span>
{ok,tut1}</pre></div>
    <p>and try it out:</p>
    <div class="example"><pre>
8&gt; <span class="bold_code">tut1:mult(3,4).</span>
12</pre></div>
    <p>In the example above the numbers are integers and the arguments
      in the functions in the code, <span class="code">N</span>, <span class="code">X</span>, <span class="code">Y</span> are
      called variables. Variables must start with a capital letter
      (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','expressions.html');">"Variables"</a></span>
      in the Erlang Reference Manual). Examples of variable could be
      <span class="code">Number</span>, <span class="code">ShoeSize</span>, <span class="code">Age</span> etc.</p>
  

  <h3><a name="id57421">2.3 
        Atoms</a></h3>
    
    <p>Atoms are another data type in Erlang. Atoms start with a small
      letter ((see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','data_types.html');">"Atom"</a></span>
      in the Erlang Reference Manual)), for example: <span class="code">charles</span>,
      <span class="code">centimeter</span>, <span class="code">inch</span>. Atoms are simply names, nothing
      else. They are not like variables which can have a value.</p>
    <p>Enter the next program (file: <span class="code">tut2.erl</span>) which could be
      useful for converting from inches to centimeters and vice versa:</p>
    <div class="example"><pre>
-module(tut2).
-export([convert/2]).

convert(M, inch) -&gt;
    M / 2.54;

convert(N, centimeter) -&gt;
    N * 2.54.</pre></div>
    <p>Compile and test:</p>
    <div class="example"><pre>
9&gt; <span class="bold_code">c(tut2).</span>
{ok,tut2}
10&gt; <span class="bold_code">tut2:convert(3, inch).</span>
1.1811023622047243
11&gt; <span class="bold_code">tut2:convert(7, centimeter).</span>
17.78</pre></div>
    <p>Notice that I have introduced decimals (floating point numbers)
      without any explanation, but I guess you can cope with that.</p>
    <p>See what happens if I enter something other than centimeter or
      inch in the convert function:</p>
    <div class="example"><pre>
12&gt; <span class="bold_code">tut2:convert(3, miles).</span>
** exception error: no function clause matching tut2:convert(3,miles) (tut2.erl, line 4)</pre></div>
    <p>The two parts of the <span class="code">convert</span> function are called its
      clauses. Here we see that "miles" is not part of either of
      the clauses. The Erlang system can't <strong>match</strong> either of
      the clauses so we get an error message <span class="code">function_clause</span>.
      The shell formats the error message nicely, but the error tuple 
      is saved in the shell's history list and can be output by the shell 
      command <span class="code">v/1</span>:</p>
    <div class="example"><pre>
13&gt; <span class="bold_code">v(12).</span>
{'EXIT',{function_clause,[{tut2,convert,
                                [3,miles],
                                [{file,"tut2.erl"},{line,4}]},
                          {erl_eval,do_apply,5,[{file,"erl_eval.erl"},{line,482}]},
                          {shell,exprs,7,[{file,"shell.erl"},{line,666}]},
                          {shell,eval_exprs,7,[{file,"shell.erl"},{line,621}]},
                          {shell,eval_loop,3,[{file,"shell.erl"},{line,606}]}]}}</pre></div>

  

  <h3><a name="id62855">2.4 
        Tuples</a></h3>
    
    <p>Now the <span class="code">tut2</span> program is hardly good programming style.
      Consider:</p>
    <div class="example"><pre>
tut2:convert(3, inch).</pre></div>
    <p>Does this mean that 3 is in inches? or that 3 is in centimeters
      and we want to convert it to inches? So Erlang has a way to group
      things together to make things more understandable. We call these
      <strong>tuples</strong>. Tuples are surrounded by "{" and "}".</p>
    <p>So we can write <span class="code">{inch,3}</span> to denote 3 inches and
      <span class="code">{centimeter,5}</span> to denote 5 centimeters. Now let's write a
      new program which converts centimeters to inches and vice versa.
      (file <span class="code">tut3.erl</span>).</p>
    <div class="example"><pre>
-module(tut3).
-export([convert_length/1]).

convert_length({centimeter, X}) -&gt;
    {inch, X / 2.54};
convert_length({inch, Y}) -&gt;
    {centimeter, Y * 2.54}.</pre></div>
    <p>Compile and test:</p>
    <div class="example"><pre>
14&gt; <span class="bold_code">c(tut3).</span>
{ok,tut3}
15&gt; <span class="bold_code">tut3:convert_length({inch, 5}).</span>
{centimeter,12.7}
16&gt; <span class="bold_code">tut3:convert_length(tut3:convert_length({inch, 5})).</span>
{inch,5.0}</pre></div>
    <p>Note on line 16 we convert 5 inches to centimeters and back
      again and reassuringly get back to the original value. I.e
      the argument to a function can be the result of another function.
      Pause for a moment and consider how line 16 (above) works.
      The argument we have given the function <span class="code">{inch,5}</span> is first
      matched against the first head clause of <span class="code">convert_length</span>
      i.e. <span class="code">convert_length({centimeter,X})</span> where it can be seen
      that <span class="code">{centimeter,X}</span> does not match <span class="code">{inch,5}</span>
      (the head is the bit before the "-&gt;"). This having failed, we try
      the head of the next clause i.e. <span class="code">convert_length({inch,Y})</span>,
      this matches and <span class="code">Y</span> get the value 5.</p>
    <p>We have shown tuples with two parts above, but tuples can have
      as many parts as we want and contain any valid Erlang
      <strong>term</strong>. For example, to represent the temperature of
      various cities of the world we could write</p>
    <div class="example"><pre>
{moscow, {c, -10}}
{cape_town, {f, 70}}
{paris, {f, 28}}</pre></div>
    <p>Tuples have a fixed number of things in them. We call each thing
      in a tuple an element. So in the tuple <span class="code">{moscow,{c,-10}}</span>,
      element 1 is <span class="code">moscow</span> and element 2 is <span class="code">{c,-10}</span>. I
      have chosen <span class="code">c</span> meaning Centigrade (or Celsius) and <span class="code">f</span>
      meaning Fahrenheit.</p>
  

  <h3><a name="id57425">2.5 
        Lists</a></h3>
    
    <p>Whereas tuples group things together, we also want to be able to
      represent lists of things. Lists in Erlang are surrounded by "["
      and "]". For example a list of the temperatures of various cities
      in the world could be:</p>
    <div class="example"><pre>
[{moscow, {c, -10}}, {cape_town, {f, 70}}, {stockholm, {c, -4}},
 {paris, {f, 28}}, {london, {f, 36}}]</pre></div>
    <p>Note that this list was so long that it didn't fit on one line.
      This doesn't matter, Erlang allows line breaks at all "sensible
      places" but not, for example, in the middle of atoms, integers
      etc.</p>
    <p>A very useful way of looking at parts of lists, is by using "|".
      This is best explained by an example using the shell.</p>
    <div class="example"><pre>
17&gt; <span class="bold_code">[First |TheRest] = [1,2,3,4,5].</span>
[1,2,3,4,5]
18&gt; <span class="bold_code">First.</span>
1
19&gt; <span class="bold_code">TheRest.</span>
[2,3,4,5]</pre></div>
    <p>We use | to separate the first elements of the list from
      the rest of the list. (<span class="code">First</span> has got value 1 and
      <span class="code">TheRest</span> value [2,3,4,5]).</p>
    <p>Another example:</p>
    <div class="example"><pre>
20&gt; <span class="bold_code">[E1, E2 | R] = [1,2,3,4,5,6,7].</span>
[1,2,3,4,5,6,7]
21&gt; <span class="bold_code">E1.</span>
1
22&gt; <span class="bold_code">E2.</span>
2
23&gt; <span class="bold_code">R.</span>
[3,4,5,6,7]</pre></div>
    <p>Here we see the use of | to get the first two elements from
      the list. Of course if we try to get more elements from the list
      than there are elements in the list we will get an error. Note
      also the special case of the list with no elements [].</p>
    <div class="example"><pre>
24&gt; <span class="bold_code">[A, B | C] = [1, 2].</span>
[1,2]
25&gt; <span class="bold_code">A.</span>
1
26&gt; <span class="bold_code">B.</span>
2
27&gt; <span class="bold_code">C.</span>
[]</pre></div>
    <p>In all the examples above, I have been using new variable names,
      not reusing the old ones: <span class="code">First</span>, <span class="code">TheRest</span>, <span class="code">E1</span>,
      <span class="code">E2</span>, <span class="code">R</span>, <span class="code">A</span>, <span class="code">B</span>, <span class="code">C</span>. The reason
      for this is that a variable can only be given a value once in its
      context (scope). I'll get back to this later, it isn't so
      peculiar as it sounds!</p>
    <p>The following example shows how we find the length of a list:</p>
    <div class="example"><pre>
-module(tut4).

-export([list_length/1]).

list_length([]) -&gt;
    0;    
list_length([First | Rest]) -&gt;
    1 + list_length(Rest).</pre></div>
    <p>Compile (file <span class="code">tut4.erl</span>) and test:</p>
    <div class="example"><pre>
28&gt; <span class="bold_code">c(tut4).</span>
{ok,tut4}
29&gt; <span class="bold_code">tut4:list_length([1,2,3,4,5,6,7]).</span>
7</pre></div>
    <p>Explanation:</p>
    <div class="example"><pre>
list_length([]) -&gt;
    0;</pre></div>
    <p>The length of an empty list is obviously 0.</p>
    <div class="example"><pre>
list_length([First | Rest]) -&gt;
    1 + list_length(Rest).</pre></div>
    <p>The length of a list with the first element <span class="code">First</span> and
      the remaining elements <span class="code">Rest</span> is 1 + the length of
      <span class="code">Rest</span>.</p>
    <p>(Advanced readers only: This is not tail recursive, there is a
      better way to write this function).</p>
    <p>In general we can say we use tuples where we would use "records"
      or "structs" in other languages and we use lists when we want to
      represent things which have varying sizes, (i.e. where we would
      use linked lists in other languages).</p>
    <p>Erlang does not have a string date type, instead strings can be
      represented by lists of ASCII characters. So the list
      <span class="code">[97,98,99]</span> is equivalent to "abc". The Erlang shell is
      "clever" and guesses the what sort of list we mean and outputs it
      in what it thinks is the most appropriate form, for example:</p>
    <div class="example"><pre>
30&gt; <span class="bold_code">[97,98,99].</span>
"abc"</pre></div>
  

  <h3><a name="id63464">2.6 
        Standard Modules and Manual Pages</a></h3>
    
    <p>Erlang has a lot of standard modules to help you do things. For
      example, the module <span class="code">io</span> contains a lot of functions to help
      you do formatted input/output. To look up information about
      standard modules, the command <span class="code">erl -man</span> can be used at
      the operating shell or command prompt (i.e. at the same place as
      that where you started <span class="code">erl</span>). Try the operating system
      shell command:</p>
    <div class="example"><pre>
% <span class="bold_code">erl -man io</span>
ERLANG MODULE DEFINITION                                    io(3)

MODULE
     io - Standard I/O Server Interface Functions

DESCRIPTION
     This module provides an  interface  to  standard  Erlang  IO
     servers. The output functions all return ok if they are suc-
     ...</pre></div>
    <p>If this doesn't work on your system, the documentation is
      included as HTML in the Erlang/OTP release, or you can read
      the documentation as HTML or download it as PDF from either of
      the sites www.erlang.se (commercial Erlang) or www.erlang.org
      (open source), for example for release R9B:</p>
    <div class="example"><pre>
http://www.erlang.org/doc/r9b/doc/index.html</pre></div>
  

  <h3><a name="id63511">2.7 
        Writing Output to a Terminal</a></h3>
    
    <p>It's nice to be able to do formatted output in these example, so
      the next example shows a simple way to use to use
      the <span class="code">io:format</span> function. Of course, just like all other
      exported functions, you can test the <span class="code">io:format</span> function in
      the shell:</p>
    <div class="example"><pre>
31&gt; <span class="bold_code">io:format("hello world~n", []).</span>
hello world
ok
32&gt; <span class="bold_code">io:format("this outputs one Erlang term: ~w~n", [hello]).</span>
this outputs one Erlang term: hello
ok
33&gt; <span class="bold_code">io:format("this outputs two Erlang terms: ~w~w~n", [hello, world]).</span>
this outputs two Erlang terms: helloworld
ok
34&gt; <span class="bold_code">io:format("this outputs two Erlang terms: ~w ~w~n", [hello, world]).</span>
this outputs two Erlang terms: hello world
ok</pre></div>
    <p>The function <span class="code">format/2</span> (i.e. <span class="code">format</span> with two
      arguments) takes two lists. The first one is nearly always a list
      written between " ". This list is printed out as it stands,
      except that each ~w is replaced by a term taken in order from
      the second list. Each ~n is replaced by a new line.
      The <span class="code">io:format/2</span> function itself returns the atom <span class="code">ok</span>
      if everything goes as planned. Like other functions in Erlang, it
      crashes if an error occurs. This is not a fault in Erlang, it is
      a deliberate policy. Erlang has sophisticated mechanisms to
      handle errors which we will show later. As an exercise, try to
      make <span class="code">io:format</span> crash, it shouldn't be difficult. But
      notice that although <span class="code">io:format</span> crashes, the Erlang shell
      itself does not crash.</p>
  

  <h3><a name="id65303">2.8 
        A Larger Example</a></h3>
    
    <p>Now for a larger example to consolidate what we have learnt so
      far. Assume we have a list of temperature readings from a number
      of cities in the world. Some of them are in Celsius (Centigrade)
      and some in Fahrenheit (as in the previous list). First let's
      convert them all to Celsius, then let's print out the data neatly.</p>
    <div class="example"><pre>
%% This module is in file tut5.erl

-module(tut5).
-export([format_temps/1]).

%% Only this function is exported
format_temps([])-&gt;                        % No output for an empty list
    ok;
format_temps([City | Rest]) -&gt;
    print_temp(convert_to_celsius(City)),
    format_temps(Rest).

convert_to_celsius({Name, {c, Temp}}) -&gt;  % No conversion needed
    {Name, {c, Temp}};
convert_to_celsius({Name, {f, Temp}}) -&gt;  % Do the conversion
    {Name, {c, (Temp - 32) * 5 / 9}}.

print_temp({Name, {c, Temp}}) -&gt;
    io:format("~-15w ~w c~n", [Name, Temp]).</pre></div>
    <div class="example"><pre>
35&gt; <span class="bold_code">c(tut5).</span>
{ok,tut5}
36&gt; <span class="bold_code">tut5:format_temps([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
moscow          -10 c
cape_town       21.11111111111111 c
stockholm       -4 c
paris           -2.2222222222222223 c
london          2.2222222222222223 c
ok</pre></div>
    <p>Before we look at how this program works, notice that we have
      added a few comments to the code. A comment starts with a %
      character and goes on to the end of the line. Note as well that
      the <span class="code">-export([format_temps/1]).</span> line only includes
      the function <span class="code">format_temps/1</span>, the other functions are
      <strong>local</strong> functions, i.e. they are not visible from outside
      the module <span class="code">tut5</span>.</p>
    <p>Note as well that when testing the program from the shell, I had
      to spread the input over two lines as the line was too long.</p>
    <p>When we call <span class="code">format_temps</span> the first time, <span class="code">City</span>
      gets the value <span class="code">{moscow,{c,-10}}</span> and <span class="code">Rest</span> is
      the rest of the list. So we call the function
      <span class="code">print_temp(convert_to_celsius({moscow,{c,-10}}))</span>.</p>
    <p>Here we see a function call as
      <span class="code">convert_to_celsius({moscow,{c,-10}})</span> as the argument to
      the function <span class="code">print_temp</span>. When we <strong>nest</strong> function
      calls like this we execute (evaluate) them from the inside out.
      I.e. we first evaluate <span class="code">convert_to_celsius({moscow,{c,-10}})</span>
      which gives the value <span class="code">{moscow,{c,-10}}</span> as the temperature
      is already in Celsius and then we evaluate
      <span class="code">print_temp({moscow,{c,-10}})</span>. The function
      <span class="code">convert_to_celsius</span> works in a similar way to
      the <span class="code">convert_length</span> function in the previous example.</p>
    <p><span class="code">print_temp</span> simply calls <span class="code">io:format</span> in a similar way
      to what has been described above. Note that ~-15w says to print
      the "term" with a field length (width) of 15 and left justify it.
      (<span class="bold_code"><a href="javascript:erlhref('../../','stdlib','io.html#fwrite-1');">io(3)</a></span>).</p>
    <p>Now we call <span class="code">format_temps(Rest)</span> with the rest of the list
      as an argument. This way of doing things is similar to the loop
      constructs in other languages. (Yes, this is recursion, but don't
      let that worry you). So the same <span class="code">format_temps</span> function is
      called again, this time <span class="code">City</span> gets the value
      <span class="code">{cape_town,{f,70}}</span> and we repeat the same procedure as
      before. We go on doing this until the list becomes empty, i.e. [],
      which causes the first clause <span class="code">format_temps([])</span> to match.
      This simply returns (results in) the atom <span class="code">ok</span>, so
      the program ends.</p>
  

  <h3><a name="id63164">2.9 
        Matching, Guards and Scope of Variables</a></h3>
    
    <p>It could be useful to find the maximum and minimum temperature
      in lists like this. Before extending the program to do this,
      let's look at functions for finding the maximum value of
      the elements in a list:</p>
    <div class="example"><pre>
-module(tut6).
-export([list_max/1]).

list_max([Head|Rest]) -&gt;
   list_max(Rest, Head).

list_max([], Res) -&gt;
    Res;
list_max([Head|Rest], Result_so_far) when Head &gt; Result_so_far -&gt;
    list_max(Rest, Head);
list_max([Head|Rest], Result_so_far)  -&gt;
    list_max(Rest, Result_so_far).</pre></div>
    <div class="example"><pre>
37&gt; <span class="bold_code">c(tut6).</span>
{ok,tut6}
38&gt; <span class="bold_code">tut6:list_max([1,2,3,4,5,7,4,3,2,1]).</span>
7</pre></div>
    <p>First note that we have two functions here with the same name
      <span class="code">list_max</span>. However each of these takes a different number
      of arguments (parameters). In Erlang these are regarded as
      completely different functions. Where we need to distinguish
      between these functions we write <span class="code">name/arity</span>, where
      <span class="code">name</span> is the name of the function and <span class="code">arity</span> is
      the number of arguments, in this case <span class="code">list_max/1</span> and
      <span class="code">list_max/2</span>.</p>
    <p>This is an example where we walk through a list "carrying" a
      value with us, in this case <span class="code">Result_so_far</span>.
      <span class="code">list_max/1</span> simply assumes that the max value of the list
      is the head of the list and calls <span class="code">list_max/2</span> with the rest
      of the list and the value of the head of the list, in the above
      this would be <span class="code">list_max([2,3,4,5,7,4,3,2,1],1)</span>. If we tried
      to use <span class="code">list_max/1</span> with an empty list or tried to use it
      with something which isn't a list at all, we would cause an error.
      Note that the Erlang philosophy is not to handle errors of this
      type in the function they occur, but to do so elsewhere. More
      about this later.</p>
    <p>In <span class="code">list_max/2</span> we walk down the list and use <span class="code">Head</span>
      instead of <span class="code">Result_so_far</span> when <span class="code">Head</span> &gt;
      <span class="code">Result_so_far</span>. <span class="code">when</span> is a special word we use before
      the -&gt; in the function to say that we should only use this part
      of the function if the test which follows is true. We call tests
      of this type a <strong>guard</strong>. If the guard isn't true (we say
      the guard fails), we try the next part of the function. In this
      case if <span class="code">Head</span> isn't greater than <span class="code">Result_so_far</span> then
      it must be smaller or equal to is, so we don't need a guard on
      the next part of the function.</p>
    <p>Some useful operators in guards are, &lt; less than, &gt;
      greater than, == equal, &gt;= greater or equal, =&lt; less or
      equal, /= not equal. (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','expressions.html');">"Guard Sequences"</a></span> in the Erlang Reference Manual).</p>
    <p>To change the above program to one which works out the minimum
      value of the element in a list, all we would need to do is to
      write &lt; instead of &gt;. (But it would be wise to change
      the name of the function to <span class="code">list_min</span> :-).</p>
    <p>Remember that I mentioned earlier that a variable could only be
      given a value once in its scope? In the above we see, for example,
      that <span class="code">Result_so_far</span> has been given several values. This is
      OK since every time we call <span class="code">list_max/2</span> we create a new
      scope and one can regard the <span class="code">Result_so_far</span> as a completely
      different variable in each scope.</p>
    <p>Another way of creating and giving a variable a value is by using
      the match operator = . So if I write <span class="code">M = 5</span>, a variable
      called <span class="code">M</span> will be created and given the value 5. If, in
      the same scope I then write <span class="code">M = 6</span>, I'll get an error. Try
      this out in the shell:</p>
    <div class="example"><pre>
39&gt; <span class="bold_code">M = 5.</span>
5
40&gt; <span class="bold_code">M = 6.</span>
** exception error: no match of right hand side value 6
41&gt; <span class="bold_code">M = M + 1.</span>
** exception error: no match of right hand side value 6
42&gt; <span class="bold_code">N = M + 1.</span>
6</pre></div>
    <p>The use of the match operator is particularly useful for pulling
      apart Erlang terms and creating new ones.</p>
    <div class="example"><pre>
43&gt; <span class="bold_code">{X, Y} = {paris, {f, 28}}.</span>
{paris,{f,28}}
44&gt; <span class="bold_code">X.</span>
paris
45&gt; <span class="bold_code">Y.</span>
{f,28}</pre></div>
    <p>Here we see that <span class="code">X</span> gets the value <span class="code">paris</span> and
      <span class="code">Y</span><span class="code">{f,28}</span>.</p>
    <p>Of course if we try to do the same again with another city, we
      get an error:</p>
    <div class="example"><pre>
46&gt; <span class="bold_code">{X, Y} = {london, {f, 36}}.</span>
** exception error: no match of right hand side value {london,{f,36}}</pre></div>
    <p>Variables can also be used to improve the readability of
      programs, for example, in the <span class="code">list_max/2</span> function above,
      we could write:</p>
    <div class="example"><pre>
list_max([Head|Rest], Result_so_far) when Head &gt; Result_so_far -&gt;
    New_result_far = Head,
    list_max(Rest, New_result_far);</pre></div>
    <p>which is possibly a little clearer.</p>
  

  <h3><a name="id63431">2.10 
        More About Lists</a></h3>
    
    <p>Remember that the | operator can be used to get the head of a
      list:</p>
    <div class="example"><pre>
47&gt; <span class="bold_code">[M1|T1] = [paris, london, rome].</span>
[paris,london,rome]
48&gt; <span class="bold_code">M1.</span>
paris
49&gt; <span class="bold_code">T1.</span>
[london,rome]</pre></div>
    <p>The | operator can also be used to add a head to a list:</p>
    <div class="example"><pre>
50&gt; <span class="bold_code">L1 = [madrid | T1].</span>
[madrid,london,rome]
51&gt; <span class="bold_code">L1.</span>
[madrid,london,rome]</pre></div>
    <p>Now an example of this when working with lists - reversing
      the order of a list:</p>
    <div class="example"><pre>
-module(tut8).

-export([reverse/1]).

reverse(List) -&gt;
    reverse(List, []).

reverse([Head | Rest], Reversed_List) -&gt;
    reverse(Rest, [Head | Reversed_List]);
reverse([], Reversed_List) -&gt;
    Reversed_List.</pre></div>
    <div class="example"><pre>
52&gt; <span class="bold_code">c(tut8).</span>
{ok,tut8}
53&gt; <span class="bold_code">tut8:reverse([1,2,3]).</span>
[3,2,1]</pre></div>
    <p>Consider how <span class="code">Reversed_List</span> is built. It starts as [], we
      then successively take off the heads of the list to be reversed
      and add them to the the <span class="code">Reversed_List</span>, as shown in
      the following:</p>
    <div class="example"><pre>
reverse([1|2,3], []) =&gt;
    reverse([2,3], [1|[]])

reverse([2|3], [1]) =&gt;
    reverse([3], [2|[1])

reverse([3|[]], [2,1]) =&gt;
    reverse([], [3|[2,1]])

reverse([], [3,2,1]) =&gt;
    [3,2,1]</pre></div>
    <p>The module <span class="code">lists</span> contains a lot of functions for
      manipulating lists, for example for reversing them, so before you
      write a list manipulating function it is a good idea to check
      that one isn't already written for you. (see
      <span class="bold_code"><a href="javascript:erlhref('../../','stdlib','lists.html');">lists(3)</a></span>).</p>
    <p>Now lets get back to the cities and temperatures, but take a more
      structured approach this time. First let's convert the whole list
      to Celsius as follows and test the function:</p>
    <div class="example"><pre>
-module(tut7).
-export([format_temps/1]).

format_temps(List_of_cities) -&gt;
    convert_list_to_c(List_of_cities).

convert_list_to_c([{Name, {f, F}} | Rest]) -&gt;
    Converted_City = {Name, {c, (F -32)* 5 / 9}},
    [Converted_City | convert_list_to_c(Rest)];

convert_list_to_c([City | Rest]) -&gt;
    [City | convert_list_to_c(Rest)];

convert_list_to_c([]) -&gt;
    [].</pre></div>
    <div class="example"><pre>
54&gt; <span class="bold_code">c(tut7).</span>
{ok, tut7}.
55&gt; <span class="bold_code">tut7:format_temps([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
[{moscow,{c,-10}},
 {cape_town,{c,21.11111111111111}},
 {stockholm,{c,-4}},
 {paris,{c,-2.2222222222222223}},
 {london,{c,2.2222222222222223}}]</pre></div>
    <p>Looking at this bit by bit:</p>
    <div class="example"><pre>
format_temps(List_of_cities) -&gt;
    convert_list_to_c(List_of_cities).</pre></div>
    <p>Here we see that <span class="code">format_temps/1</span> calls
      <span class="code">convert_list_to_c/1</span>. <span class="code">convert_list_to_c/1</span> takes off
      the head of the <span class="code">List_of_cities</span>, converts it to Celsius if
      needed. The | operator is used to add the (maybe) converted
      to the converted rest of the list:</p>
    <div class="example"><pre>
[Converted_City | convert_list_to_c(Rest)];</pre></div>
    <p>or</p>
    <div class="example"><pre>
[City | convert_list_to_c(Rest)];</pre></div>
    <p>We go on doing this until we get to the end of the list (i.e.
      the list is empty:</p>
    <div class="example"><pre>
convert_list_to_c([]) -&gt;
    [].</pre></div>
    <p>Now we have converted the list, we add a function to print it:</p>
    <div class="example"><pre>
-module(tut7).
-export([format_temps/1]).

format_temps(List_of_cities) -&gt;
    Converted_List = convert_list_to_c(List_of_cities),
    print_temp(Converted_List).

convert_list_to_c([{Name, {f, F}} | Rest]) -&gt;
    Converted_City = {Name, {c, (F -32)* 5 / 9}},
    [Converted_City | convert_list_to_c(Rest)];

convert_list_to_c([City | Rest]) -&gt;
    [City | convert_list_to_c(Rest)];

convert_list_to_c([]) -&gt;
    [].

print_temp([{Name, {c, Temp}} | Rest]) -&gt;
    io:format("~-15w ~w c~n", [Name, Temp]),
    print_temp(Rest);
print_temp([]) -&gt;
    ok.</pre></div>
    <div class="example"><pre>
56&gt; <span class="bold_code">c(tut7).</span>
{ok,tut7}
57&gt; <span class="bold_code">tut7:format_temps([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
moscow          -10 c
cape_town       21.11111111111111 c
stockholm       -4 c
paris           -2.2222222222222223 c
london          2.2222222222222223 c
ok</pre></div>
    <p>We now have to add a function to find the cities with
      the maximum and minimum temperatures. The program below isn't
      the most efficient way of doing this as we walk through the list
      of cities four times. But it is better to first strive for
      clarity and correctness and to make programs efficient only if
      really needed.</p>
    <div class="example"><pre>
-module(tut7).
-export([format_temps/1]).

format_temps(List_of_cities) -&gt;
    Converted_List = convert_list_to_c(List_of_cities),
    print_temp(Converted_List),
    {Max_city, Min_city} = find_max_and_min(Converted_List),
    print_max_and_min(Max_city, Min_city).

convert_list_to_c([{Name, {f, Temp}} | Rest]) -&gt;
    Converted_City = {Name, {c, (Temp -32)* 5 / 9}},
    [Converted_City | convert_list_to_c(Rest)];

convert_list_to_c([City | Rest]) -&gt;
    [City | convert_list_to_c(Rest)];

convert_list_to_c([]) -&gt;
    [].

print_temp([{Name, {c, Temp}} | Rest]) -&gt;
    io:format("~-15w ~w c~n", [Name, Temp]),
    print_temp(Rest);
print_temp([]) -&gt;
    ok.

find_max_and_min([City | Rest]) -&gt;
    find_max_and_min(Rest, City, City).

find_max_and_min([{Name, {c, Temp}} | Rest], 
         {Max_Name, {c, Max_Temp}}, 
         {Min_Name, {c, Min_Temp}}) -&gt;
    if 
        Temp &gt; Max_Temp -&gt;
            Max_City = {Name, {c, Temp}};           % Change
        true -&gt; 
            Max_City = {Max_Name, {c, Max_Temp}} % Unchanged
    end,
    if
         Temp &lt; Min_Temp -&gt;
            Min_City = {Name, {c, Temp}};           % Change
        true -&gt; 
            Min_City = {Min_Name, {c, Min_Temp}} % Unchanged
    end,
    find_max_and_min(Rest, Max_City, Min_City);

find_max_and_min([], Max_City, Min_City) -&gt;
    {Max_City, Min_City}.

print_max_and_min({Max_name, {c, Max_temp}}, {Min_name, {c, Min_temp}}) -&gt;
    io:format("Max temperature was ~w c in ~w~n", [Max_temp, Max_name]),
    io:format("Min temperature was ~w c in ~w~n", [Min_temp, Min_name]).</pre></div>
<div class="example"><pre>
58&gt; <span class="bold_code">c(tut7).</span>
{ok, tut7}
59&gt; <span class="bold_code">tut7:format_temps([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
moscow          -10 c
cape_town       21.11111111111111 c
stockholm       -4 c
paris           -2.2222222222222223 c
london          2.2222222222222223 c
Max temperature was 21.11111111111111 c in cape_town
Min temperature was -10 c in moscow
ok</pre></div>
  

  <h3><a name="id66137">2.11 
        If and Case</a></h3>
    
    <p>The function <span class="code">find_max_and_min</span> works out the maximum and
      minimum temperature. We have introduced a new construct here
      <span class="code">if</span>. If works as follows:</p>
    <div class="example"><pre>
if
    Condition 1 -&gt;
        Action 1;
    Condition 2 -&gt;
        Action 2;
    Condition 3 -&gt;
        Action 3;
    Condition 4 -&gt;
        Action 4
end</pre></div>
    <p>Note there is no ";" before <span class="code">end</span>! Conditions are the same
      as guards, tests which succeed or fail. Erlang starts at the top
      until it finds a condition which succeeds and then it evaluates
      (performs) the action following the condition and ignores all
      other conditions and action before the <span class="code">end</span>. If no
      condition matches, there will be a run-time failure. A condition
      which always is succeeds is the atom, <span class="code">true</span> and this is
      often used last in an <span class="code">if</span> meaning do the action following
      the <span class="code">true</span> if all other conditions have failed.</p>
    <p>The following is a short program to show the workings of
      <span class="code">if</span>.</p>
    <div class="example"><pre>
-module(tut9).
-export([test_if/2]).

test_if(A, B) -&gt;
    if 
        A == 5 -&gt;
            io:format("A == 5~n", []),
            a_equals_5;
        B == 6 -&gt;
            io:format("B == 6~n", []),
            b_equals_6;
        A == 2, B == 3 -&gt;                      %i.e. A equals 2 and B equals 3
            io:format("A == 2, B == 3~n", []),
            a_equals_2_b_equals_3;
        A == 1 ; B == 7 -&gt;                     %i.e. A equals 1 or B equals 7
            io:format("A == 1 ; B == 7~n", []),
            a_equals_1_or_b_equals_7
    end.</pre></div>
    <p>Testing this program gives:</p>
    <div class="example"><pre>
60&gt; <span class="bold_code">c(tut9).</span>
{ok,tut9}
61&gt; <span class="bold_code">tut9:test_if(5,33).</span>
A == 5
a_equals_5
62&gt; <span class="bold_code">tut9:test_if(33,6).</span>
B == 6
b_equals_6
63&gt; <span class="bold_code">tut9:test_if(2, 3).</span>
A == 2, B == 3
a_equals_2_b_equals_3
64&gt; <span class="bold_code">tut9:test_if(1, 33).</span>
A == 1 ; B == 7
a_equals_1_or_b_equals_7
65&gt; <span class="bold_code">tut9:test_if(33, 7).</span>
A == 1 ; B == 7
a_equals_1_or_b_equals_7
66&gt; <span class="bold_code">tut9:test_if(33, 33).</span>
** exception error: no true branch found when evaluating an if expression
     in function  tut9:test_if/2 (tut9.erl, line 5)</pre></div>
    <p>Notice that <span class="code">tut9:test_if(33,33)</span> did not cause any
      condition to succeed so we got the run time error
      <span class="code">if_clause</span>, here nicely formatted by the shell. See the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','expressions.html');">"Guard Sequences"</a></span> in the Erlang Reference Manual for details
      of the many guard tests available. <span class="code">case</span> is another
      construct in Erlang. Recall that we wrote the
      <span class="code">convert_length</span> function as:</p>
    <div class="example"><pre>
convert_length({centimeter, X}) -&gt;
    {inch, X / 2.54};
convert_length({inch, Y}) -&gt;
    {centimeter, Y * 2.54}.</pre></div>
    <p>We could also write the same program as:</p>
    <div class="example"><pre>
-module(tut10).
-export([convert_length/1]).

convert_length(Length) -&gt;
    case Length of
        {centimeter, X} -&gt;
            {inch, X / 2.54};
        {inch, Y} -&gt;
            {centimeter, Y * 2.54}
    end.</pre></div>
    <div class="example"><pre>
67&gt; <span class="bold_code">c(tut10).</span>
{ok,tut10}
68&gt; <span class="bold_code">tut10:convert_length({inch, 6}).</span>
{centimeter,15.24}
69&gt; <span class="bold_code">tut10:convert_length({centimeter, 2.5}).</span>
{inch,0.984251968503937}</pre></div>
    <p>Notice that both <span class="code">case</span> and <span class="code">if</span> have <strong>return values</strong>, i.e. in the above example <span class="code">case</span> returned
      either <span class="code">{inch,X/2.54}</span> or <span class="code">{centimeter,Y*2.54}</span>.
      The behaviour of <span class="code">case</span> can also be modified by using guards.
      An example should hopefully clarify this. The following example
      tells us the length of a month, given the year. We need to know
      the year of course, since February has 29 days in a leap year.</p>
    <div class="example"><pre>
-module(tut11).
-export([month_length/2]).

month_length(Year, Month) -&gt;
    %% All years divisible by 400 are leap
    %% Years divisible by 100 are not leap (except the 400 rule above)
    %% Years divisible by 4 are leap (except the 100 rule above)
    Leap = if
        trunc(Year / 400) * 400 == Year -&gt;
            leap;
        trunc(Year / 100) * 100 == Year -&gt;
            not_leap;
        trunc(Year / 4) * 4 == Year -&gt;
            leap;
        true -&gt;
            not_leap
    end,  
    case Month of
        sep -&gt; 30;
        apr -&gt; 30;
        jun -&gt; 30;
        nov -&gt; 30;
        feb when Leap == leap -&gt; 29;
        feb -&gt; 28;
        jan -&gt; 31;
        mar -&gt; 31;
        may -&gt; 31;
        jul -&gt; 31;
        aug -&gt; 31;
        oct -&gt; 31;
        dec -&gt; 31
    end.</pre></div>
    <div class="example"><pre>
70&gt; <span class="bold_code">c(tut11).</span>
{ok,tut11}
71&gt; <span class="bold_code">tut11:month_length(2004, feb).</span>
29
72&gt; <span class="bold_code">tut11:month_length(2003, feb).</span>
28
73&gt; <span class="bold_code">tut11:month_length(1947, aug).</span>
31</pre></div>
  

  <h3><a name="id66368">2.12 
        Built In Functions (BIFs)</a></h3>
    
    <p>Built in functions BIFs are functions which for some reason is
      built in to the Erlang virtual machine. BIFs often implement 
      functionality that is impossible to implement in Erlang or is to
      inefficient to implement in Erlang. Some BIFs can be called 
      by use of the function name only but they are by default belonging
      to the erlang module so for example the call to the BIF <span class="code">trunc</span>
      below is equivalent with a call to <span class="code">erlang:trunc</span>.</p>
    <p>As you can see, we first find out if a year is leap or not. If a
      year is divisible by 400, it is a leap year. To find this out we
      first divide the year by 400 and use the built in function
      <span class="code">trunc</span> (more later) to cut off any decimals. We then
      multiply by 400 again and see if we get back the same value. For
      example, year 2004:</p>
    <div class="example"><pre>
2004 / 400 = 5.01
trunc(5.01) = 5
5 * 400 = 2000</pre></div>
    <p>and we can see that we got back 2000 which is not the same as
      2004, so 2004 isn't divisible by 400. Year 2000:</p>
    <div class="example"><pre>
2000 / 400 = 5.0
trunc(5.0) = 5
5 * 400 = 2000</pre></div>
    <p>so we have a leap year. The next two tests if the year is
      divisible by 100 or 4 are done in the same way. The first
      <span class="code">if</span> returns <span class="code">leap</span> or <span class="code">not_leap</span> which lands up
      in the variable <span class="code">Leap</span>. We use this variable in the guard
      for <span class="code">feb</span> in the following <span class="code">case</span> which tells us how
      long the month is.</p>
    <p>This example showed the use of <span class="code">trunc</span>, an easier way would
      be to use the Erlang operator <span class="code">rem</span> which gives the remainder
      after division. For example:</p>
    <div class="example"><pre>
74&gt; <span class="bold_code">2004 rem 400.</span>
4</pre></div>
    <p>so instead of writing</p>
    <div class="example"><pre>
trunc(Year / 400) * 400 == Year -&gt;
    leap;</pre></div>
    <p>we could write</p>
    <div class="example"><pre>
Year rem 400 == 0 -&gt;
    leap;</pre></div>
    <p>There are many other built in functions (BIF) such as
      <span class="code">trunc</span>. Only a few built in functions can be used in guards,
      and you cannot use functions you have defined yourself in guards.
      (see the chapter
      <span class="bold_code"><a href="javascript:erlhref('../../','doc/reference_manual','expressions.html');">"Guard Sequences"</a></span> in the Erlang Reference Manual) (Aside for
      advanced readers: This is to ensure that guards don't have side
      effects). Let's play with a few of these functions in the shell:</p>
    <div class="example"><pre>
75&gt; <span class="bold_code">trunc(5.6).</span>
5
76&gt; <span class="bold_code">round(5.6).</span>
6
77&gt; <span class="bold_code">length([a,b,c,d]).</span>
4
78&gt; <span class="bold_code">float(5).</span>
5.0
79&gt; <span class="bold_code">is_atom(hello).</span>
true
80&gt; <span class="bold_code">is_atom("hello").</span>
false
81&gt; <span class="bold_code">is_tuple({paris, {c, 30}}).</span>
true
82&gt; <span class="bold_code">is_tuple([paris, {c, 30}]).</span>
false</pre></div>
    <p>All the above can be used in guards. Now for some which can't be
      used in guards:</p>
    <div class="example"><pre>
83&gt; <span class="bold_code">atom_to_list(hello).</span>
"hello"
84&gt; <span class="bold_code">list_to_atom("goodbye").</span>
goodbye
85&gt; <span class="bold_code">integer_to_list(22).</span>
"22"</pre></div>
    <p>The 3 BIFs above do conversions which would be difficult (or
      impossible) to do in Erlang.</p>
  

  <h3><a name="id66559">2.13 
        Higher Order Functions (Funs)</a></h3>
    
    <p>Erlang, like most modern functional programming languages, has
      higher order functions. We start with an example using the shell:</p>
    <div class="example"><pre>
86&gt; <span class="bold_code">Xf = fun(X) -&gt; X * 2 end.</span>
#Fun&lt;erl_eval.5.123085357&gt;
87&gt; <span class="bold_code">Xf(5).</span>
10</pre></div>
    <p>What we have done here is to define a function which doubles
      the value of number and assign this function to a variable. Thus
      <span class="code">Xf(5)</span> returned the value 10. Two useful functions when
      working with lists are <span class="code">foreach</span> and <span class="code">map</span>, which are
      defined as follows:</p>
    <div class="example"><pre>
foreach(Fun, [First|Rest]) -&gt;
    Fun(First),
    foreach(Fun, Rest);
foreach(Fun, []) -&gt;
    ok.

map(Fun, [First|Rest]) -&gt; 
    [Fun(First)|map(Fun,Rest)];
map(Fun, []) -&gt; 
    [].</pre></div>
    <p>These two functions are provided in the standard module
      <span class="code">lists</span>. <span class="code">foreach</span> takes a list and applies a fun to
      every element in the list, <span class="code">map</span> creates a new list by
      applying a fun to every element in a list. Going back to
      the shell, we start by using <span class="code">map</span> and a fun to add 3 to
      every element of a list:</p>
    <div class="example"><pre>
88&gt; <span class="bold_code">Add_3 = fun(X) -&gt; X + 3 end.</span>
#Fun&lt;erl_eval.5.123085357&gt;
89&gt; <span class="bold_code">lists:map(Add_3, [1,2,3]).</span>
[4,5,6]</pre></div>
    <p>Now lets print out the temperatures in a list of cities (yet
      again):</p>
    <div class="example"><pre>
90&gt; <span class="bold_code">Print_City = fun({City, {X, Temp}}) -&gt; io:format("~-15w ~w ~w~n",</span>
<span class="bold_code">[City, X, Temp]) end.</span>
#Fun&lt;erl_eval.5.123085357&gt;
91&gt; <span class="bold_code">lists:foreach(Print_City, [{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
moscow          c -10
cape_town       f 70
stockholm       c -4
paris           f 28
london          f 36
ok</pre></div>
    <p>We will now define a fun which can be used to go through a list
      of cities and temperatures and transform them all to Celsius.</p>
    <div class="example"><pre>
-module(tut13).

-export([convert_list_to_c/1]).

convert_to_c({Name, {f, Temp}}) -&gt;
    {Name, {c, trunc((Temp - 32) * 5 / 9)}};
convert_to_c({Name, {c, Temp}}) -&gt;
    {Name, {c, Temp}}.

convert_list_to_c(List) -&gt;
    lists:map(fun convert_to_c/1, List).</pre></div>
    <div class="example"><pre>
92&gt; <span class="bold_code">tut13:convert_list_to_c([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
[{moscow,{c,-10}},
 {cape_town,{c,21}},
 {stockholm,{c,-4}},
 {paris,{c,-2}},
 {london,{c,2}}]</pre></div>
    <p>The <span class="code">convert_to_c</span> function is the same as before, but we
      use it as a fun:</p>
    <div class="example"><pre>
lists:map(fun convert_to_c/1, List)</pre></div>
    <p>When we use a function defined elsewhere as a fun we can refer
      to it as <span class="code">Function/Arity</span> (remember that <span class="code">Arity</span> =
      number of arguments). So in the <span class="code">map</span> call we write
      <span class="code">lists:map(fun convert_to_c/1, List)</span>. As you can see
      <span class="code">convert_list_to_c</span> becomes much shorter and easier to
      understand.</p>
    <p>The standard module <span class="code">lists</span> also contains a function
      <span class="code">sort(Fun, List)</span> where <span class="code">Fun</span> is a fun with two
      arguments. This fun should return <span class="code">true</span> if the the first
      argument is less than the second argument, or else <span class="code">false</span>.
      We add sorting to the <span class="code">convert_list_to_c</span>:</p>
    <div class="example"><pre>
-module(tut13).

-export([convert_list_to_c/1]).

convert_to_c({Name, {f, Temp}}) -&gt;
    {Name, {c, trunc((Temp - 32) * 5 / 9)}};
convert_to_c({Name, {c, Temp}}) -&gt;
    {Name, {c, Temp}}.

convert_list_to_c(List) -&gt;
    New_list = lists:map(fun convert_to_c/1, List),
    lists:sort(fun({_, {c, Temp1}}, {_, {c, Temp2}}) -&gt;
                       Temp1 &lt; Temp2 end, New_list).</pre></div>
    <div class="example"><pre>
93&gt; <span class="bold_code">c(tut13).</span>
{ok,tut13}
94&gt; <span class="bold_code">tut13:convert_list_to_c([{moscow, {c, -10}}, {cape_town, {f, 70}},</span>
<span class="bold_code">{stockholm, {c, -4}}, {paris, {f, 28}}, {london, {f, 36}}]).</span>
[{moscow,{c,-10}},
 {stockholm,{c,-4}},
 {paris,{c,-2}},
 {london,{c,2}},
 {cape_town,{c,21}}]</pre></div>
    <p>In <span class="code">sort</span> we use the fun:</p>
    <div class="example"><pre>
fun({_, {c, Temp1}}, {_, {c, Temp2}}) -&gt; Temp1 &lt; Temp2 end,</pre></div>
    <p>Here we introduce the concept of an <strong>anonymous variable</strong>
      "_". This is simply shorthand for a variable which is going to
      get a value, but we will ignore the value. This can be used
      anywhere suitable, not just in fun's. <span class="code">Temp1 &lt; Temp2</span>
      returns <span class="code">true</span> if <span class="code">Temp1</span> is less than <span class="code">Temp2</span>.</p>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 1996-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>