Sophie

Sophie

distrib > Fedora > 17 > x86_64 > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 104

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 -- Funs</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>Programming Examples</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="Records" expanded="false">Records<ul>
<li><a href="records.html">
              Top of chapter
            </a></li>
<li title="Records vs Tuples"><a href="records.html#id60765">Records vs Tuples</a></li>
<li title="Defining a Record"><a href="records.html#id60728">Defining a Record</a></li>
<li title="Creating a Record"><a href="records.html#id59920">Creating a Record</a></li>
<li title="Accessing a Record Field"><a href="records.html#id60048">Accessing a Record Field</a></li>
<li title="Updating a Record"><a href="records.html#id61983">Updating a Record</a></li>
<li title="Type Testing"><a href="records.html#id60031">Type Testing</a></li>
<li title="Pattern Matching"><a href="records.html#id60080">Pattern Matching</a></li>
<li title="Nested Records"><a href="records.html#id61405">Nested Records</a></li>
<li title="Example"><a href="records.html#id57989">Example</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Funs" expanded="true">Funs<ul>
<li><a href="funs.html">
              Top of chapter
            </a></li>
<li title="Example 1 - map"><a href="funs.html#id64362">Example 1 - map</a></li>
<li title="Example 2 - foreach"><a href="funs.html#id57513">Example 2 - foreach</a></li>
<li title="The Syntax of Funs"><a href="funs.html#id61441">The Syntax of Funs</a></li>
<li title="Variable Bindings Within a Fun"><a href="funs.html#id61096">Variable Bindings Within a Fun</a></li>
<li title="Funs and the Module Lists"><a href="funs.html#id61883">Funs and the Module Lists</a></li>
<li title="Funs Which Return Funs"><a href="funs.html#id62549">Funs Which Return Funs</a></li>
</ul>
</li>
<li id="no" title="List Comprehensions" expanded="false">List Comprehensions<ul>
<li><a href="list_comprehensions.html">
              Top of chapter
            </a></li>
<li title="Simple Examples"><a href="list_comprehensions.html#id63964">Simple Examples</a></li>
<li title="Quick Sort"><a href="list_comprehensions.html#id64034">Quick Sort</a></li>
<li title="Permutations"><a href="list_comprehensions.html#id64089">Permutations</a></li>
<li title="Pythagorean Triplets"><a href="list_comprehensions.html#id64141">Pythagorean Triplets</a></li>
<li title="Simplifications with List Comprehensions"><a href="list_comprehensions.html#id64218">Simplifications with List Comprehensions</a></li>
<li title="Variable Bindings in List Comprehensions"><a href="list_comprehensions.html#id64241">Variable Bindings in List Comprehensions</a></li>
</ul>
</li>
<li id="no" title="Bit Syntax" expanded="false">Bit Syntax<ul>
<li><a href="bit_syntax.html">
              Top of chapter
            </a></li>
<li title="Introduction"><a href="bit_syntax.html#id64741">Introduction</a></li>
<li title="A Lexical Note"><a href="bit_syntax.html#id65026">A Lexical Note</a></li>
<li title="Segments"><a href="bit_syntax.html#id65049">Segments</a></li>
<li title="Defaults"><a href="bit_syntax.html#id65237">Defaults</a></li>
<li title="Constructing Binaries and Bitstrings"><a href="bit_syntax.html#id65297">Constructing Binaries and Bitstrings</a></li>
<li title="Matching Binaries"><a href="bit_syntax.html#id65485">Matching Binaries</a></li>
<li title="Appending to a Binary"><a href="bit_syntax.html#id65619">Appending to a Binary</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>2 Funs</h1>
  

  <h3><a name="id64362">2.1 
        Example 1 - map</a></h3>
    
    <p>If we want to double every element in a list, we could write a
      function named <span class="code">double</span>:</p>
    <div class="example"><pre>
double([H|T]) -&gt; [2*H|double(T)];
double([])    -&gt; [].</pre></div>
    <p>This function obviously doubles the argument entered as input
      as follows:</p>
    <div class="example"><pre>
&gt; <span class="bold_code">double([1,2,3,4]).</span>
[2,4,6,8]</pre></div>
    <p>We now add the function <span class="code">add_one</span>, which adds one to every
      element in a list:</p>
    <div class="example"><pre>
add_one([H|T]) -&gt; [H+1|add_one(T)];
add_one([])    -&gt; [].</pre></div>
    <p>These functions, <span class="code">double</span> and <span class="code">add_one</span>, have a very
      similar structure. We can exploit this fact and write a function
      <span class="code">map</span> which expresses this similarity:</p>
<div class="example"><pre>

map(F, [H|T]) -&gt; [F(H)|map(F, T)];
map(F, [])    -&gt; [].</pre></div>    <p>We can now express the functions <span class="code">double</span> and
      <span class="code">add_one</span> in terms of <span class="code">map</span> as follows:</p>
    <div class="example"><pre>
double(L)  -&gt; map(fun(X) -&gt; 2*X end, L).
add_one(L) -&gt; map(fun(X) -&gt; 1 + X end, L).</pre></div>
    <p><span class="code">map(F, List)</span> is a function which takes a function
      <span class="code">F</span> and a list <span class="code">L</span> as arguments and returns the new
      list which is obtained by applying <span class="code">F</span> to each of
      the elements in <span class="code">L</span>.</p>
    <p>The process of abstracting out the common features of a number
      of different programs is called procedural abstraction.
      Procedural abstraction can be used in order to write several
      different functions which have a similar structure, but differ
      only in some minor detail. This is done as follows:</p>
    <ul>
      <li>write one function which represents the common features of
       these functions</li>
      <li>parameterize the difference in terms of functions which
       are passed as arguments to the common function.</li>
    </ul>
  

  <h3><a name="id57513">2.2 
        Example 2 - foreach</a></h3>
    
    <p>This example illustrates procedural abstraction. Initially, we
      show the following two examples written as conventional
      functions:</p>
    <ul>
      <li>all elements of a list are printed onto a stream</li>
      <li>a message is broadcast to a list of processes.</li>
    </ul>
    <div class="example"><pre>
print_list(Stream, [H|T]) -&gt;
    io:format(Stream, "~p~n", [H]),
    print_list(Stream, T);
print_list(Stream, []) -&gt;
    true.</pre></div>
    <div class="example"><pre>
broadcast(Msg, [Pid|Pids]) -&gt;
    Pid ! Msg,
    broadcast(Msg, Pids);
broadcast(_, []) -&gt;
    true.</pre></div>
    <p>Both these functions have a very similar structure. They both
      iterate over a list doing something to each element in the list.
      The "something" has to be carried round as an extra argument to
      the function which does this.</p>
    <p>The function <span class="code">foreach</span> expresses this similarity:</p>
<div class="example"><pre>

foreach(F, [H|T]) -&gt;
    F(H),
    foreach(F, T);
foreach(F, []) -&gt;
    ok.</pre></div>    <p>Using <span class="code">foreach</span>, <span class="code">print_list</span> becomes:</p>
    <div class="example"><pre>
foreach(fun(H) -&gt; io:format(S, "~p~n",[H]) end, L)</pre></div>
    <p><span class="code">broadcast</span> becomes:</p>
    <div class="example"><pre>
foreach(fun(Pid) -&gt; Pid ! M end, L)</pre></div>
    <p><span class="code">foreach</span> is evaluated for its side-effect and not its
      value. <span class="code">foreach(Fun ,L)</span> calls <span class="code">Fun(X)</span> for each
      element <span class="code">X</span> in <span class="code">L</span> and the processing occurs in
      the order in which the elements were defined in <span class="code">L</span>.
      <span class="code">map</span> does not define the order in which its elements are
      processed.</p>
  

  <h3><a name="id61441">2.3 
        The Syntax of Funs</a></h3>
    
    <p>Funs are written with the syntax:</p>
    <div class="example"><pre>
F = fun (Arg1, Arg2, ... ArgN) -&gt;
        ...
    end</pre></div>
    <p>This creates an anonymous function of <span class="code">N</span> arguments and
      binds it to the variable <span class="code">F</span>.</p>
    <p>If we have already written a function in the same module and
      wish to pass this function as an argument, we can use
      the following syntax:</p>
    <div class="example"><pre>
F = fun FunctionName/Arity</pre></div>
    <p>With this form of function reference, the function which is
      referred to does not need to be exported from the module.</p>
    <p>We can also refer to a function defined in a different module
      with the following syntax:</p>
    <div class="example"><pre>
F = {Module, FunctionName}</pre></div>
    <p>In this case, the function must be exported from the module in
      question.</p>
    <p>The follow program illustrates the different ways of creating
      funs:</p>
<div class="example"><pre>

-module(fun_test).
-export([t1/0, t2/0, t3/0, t4/0, double/1]).
-import(lists, [map/2]).

t1() -&gt; map(fun(X) -&gt; 2 * X end, [1,2,3,4,5]).

t2() -&gt; map(fun double/1, [1,2,3,4,5]).

t3() -&gt; map({?MODULE, double}, [1,2,3,4,5]).

double(X) -&gt; X * 2.</pre></div>    <p>We can evaluate the fun <span class="code">F</span> with the syntax:</p>
    <div class="example"><pre>
F(Arg1, Arg2, ..., Argn)</pre></div>
    <p>To check whether a term is a fun, use the test
      <span class="code">is_function/1</span> in a guard. Example:</p>
    <div class="example"><pre>
f(F, Args) when is_function(F) -&gt;
   apply(F, Args);
f(N, _) when is_integer(N) -&gt;
   N.</pre></div>
    <p>Funs are a distinct type. The BIFs erlang:fun_info/1,2 can
      be used to retrieve information about a fun, and the BIF
      erlang:fun_to_list/1 returns a textual representation of a fun.
      The check_process_code/2 BIF returns true if the process
      contains funs that depend on the old version of a module.</p>
    <div class="note">
<div class="label">Note</div>
<div class="content"><p>
      <p>In OTP R5 and earlier releases, funs were represented using
        tuples.</p>
    </p></div>
</div>
  

  <h3><a name="id61096">2.4 
        Variable Bindings Within a Fun</a></h3>
    
    <p>The scope rules for variables which occur in funs are as
      follows:</p>
    <ul>
      <li>All variables which occur in the head of a fun are assumed
       to be "fresh" variables.</li>
      <li>Variables which are defined before the fun, and which
       occur in function calls or guard tests within the fun, have
       the values they had outside the fun.</li>
      <li>No variables may be exported from a fun.</li>
    </ul>
    <p>The following examples illustrate these rules:</p>
    <div class="example"><pre>
print_list(File, List) -&gt;
    {ok, Stream} = file:open(File, write),
    foreach(fun(X) -&gt; io:format(Stream,"~p~n",[X]) end, List),
    file:close(Stream).</pre></div>
    <p>In the above example, the variable <span class="code">X</span> which is defined in
      the head of the fun is a new variable. The value of the variable
      <span class="code">Stream</span> which is used within within the fun gets its value
      from the <span class="code">file:open</span> line.</p>
    <p>Since any variable which occurs in the head of a fun is
      considered a new variable it would be equally valid to write:</p>
    <div class="example"><pre>
print_list(File, List) -&gt;
    {ok, Stream} = file:open(File, write),
    foreach(fun(File) -&gt; 
                io:format(Stream,"~p~n",[File]) 
            end, List),
    file:close(Stream).</pre></div>
    <p>In this example, <span class="code">File</span> is used as the new variable
      instead of <span class="code">X</span>. This is rather silly since code in the body
      of the fun cannot refer to the variable <span class="code">File</span> which is
      defined outside the fun. Compiling this example will yield
      the diagnostic:</p>
    <div class="example"><pre>
./FileName.erl:Line: Warning: variable 'File' 
      shadowed in 'lambda head'</pre></div>
    <p>This reminds us that the variable <span class="code">File</span> which is defined
      inside the fun collides with the variable <span class="code">File</span> which is
      defined outside the fun.</p>
    <p>The rules for importing variables into a fun has the consequence
      that certain pattern matching operations have to be moved into
      guard expressions and cannot be written in the head of the fun.
      For example, we might write the following code if we intend
      the first clause of <span class="code">F</span> to be evaluated when the value of
      its argument is <span class="code">Y</span>:</p>
    <div class="example"><pre>
f(...) -&gt;
    Y = ...
    map(fun(X) when X == Y -&gt;
             ;
           (_) -&gt;
             ...
        end, ...)
    ...</pre></div>
    <p>instead of</p>
    <div class="example"><pre>
f(...) -&gt;
    Y = ...
    map(fun(Y) -&gt;
             ;
           (_) -&gt;
             ...
        end, ...)
    ...</pre></div>
  

  <h3><a name="id61883">2.5 
        Funs and the Module Lists</a></h3>
    
    <p>The following examples show a dialogue with the Erlang shell.
      All the higher order functions discussed are exported from
      the module <span class="code">lists</span>.</p>

    <h4>map</h4>
      
<div class="example"><pre>

map(F, [H|T]) -&gt; [F(H)|map(F, T)];
map(F, [])    -&gt; [].</pre></div>      <p><span class="code">map</span> takes a function of one argument and a list of
        terms. It returns the list obtained by applying the function
        to every argument in the list.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">Double = fun(X) -&gt; 2 * X end.</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">lists:map(Double, [1,2,3,4,5]).</span>
[2,4,6,8,10]</pre></div>
      <p>When a new fun is defined in the shell, the value of the Fun
        is printed as <span class="code">Fun#&lt;erl_eval&gt;</span>.</p>
    

    <h4>any</h4>
      
<div class="example"><pre>

any(Pred, [H|T]) -&gt;
    case Pred(H) of
        true  -&gt;  true;
        false -&gt;  any(Pred, T)
    end;
any(Pred, []) -&gt;
    false.</pre></div>      <p><span class="code">any</span> takes a predicate <span class="code">P</span> of one argument and a
        list of terms. A predicate is a function which returns
        <span class="code">true</span> or <span class="code">false</span>. <span class="code">any</span> is true if there is a
        term <span class="code">X</span> in the list such that <span class="code">P(X)</span> is <span class="code">true</span>.</p>
      <p>We define a predicate <span class="code">Big(X)</span> which is <span class="code">true</span> if
        its argument is greater that 10.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">Big =  fun(X) -&gt; if X &gt; 10 -&gt; true; true -&gt; false end end.</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">lists:any(Big, [1,2,3,4]).</span>
false
&gt; <span class="bold_code">lists:any(Big, [1,2,3,12,5]).</span>
true</pre></div>
    

    <h4>all</h4>
      
<div class="example"><pre>

all(Pred, [H|T]) -&gt;
    case Pred(H) of
        true  -&gt;  all(Pred, T);
        false -&gt;  false
    end;
all(Pred, []) -&gt;
    true.</pre></div>      <p><span class="code">all</span> has the same arguments as <span class="code">any</span>. It is true
        if the predicate applied to all elements in the list is true.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:all(Big, [1,2,3,4,12,6]).</span>   
false
&gt; <span class="bold_code">lists:all(Big, [12,13,14,15]).</span>       
true</pre></div>
    

    <h4>foreach</h4>
      
<div class="example"><pre>

foreach(F, [H|T]) -&gt;
    F(H),
    foreach(F, T);
foreach(F, []) -&gt;
    ok.</pre></div>      <p><span class="code">foreach</span> takes a function of one argument and a list of
        terms. The function is applied to each argument in the list.
        <span class="code">foreach</span> returns <span class="code">ok</span>. It is used for its
        side-effect only.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:foreach(fun(X) -&gt; io:format("~w~n",[X]) end, [1,2,3,4]).</span> 
1
2
3
4
ok</pre></div>
    

    <h4>foldl</h4>
      
<div class="example"><pre>

foldl(F, Accu, [Hd|Tail]) -&gt;
    foldl(F, F(Hd, Accu), Tail);
foldl(F, Accu, []) -&gt; Accu.</pre></div>      <p><span class="code">foldl</span> takes a function of two arguments, an
        accumulator and a list. The function is called with two
        arguments. The first argument is the successive elements in
        the list, the second argument is the accumulator. The function
        must return a new accumulator which is used the next time
        the function is called.</p>
      <p>If we have a list of lists <span class="code">L = ["I","like","Erlang"]</span>,
        then we can sum the lengths of all the strings in <span class="code">L</span> as
        follows:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">L = ["I","like","Erlang"].</span>
["I","like","Erlang"]
10&gt; <span class="bold_code">lists:foldl(fun(X, Sum) -&gt; length(X) + Sum end, 0, L).</span>                    
11</pre></div>
      <p><span class="code">foldl</span> works like a <span class="code">while</span> loop in an imperative
        language:</p>
      <div class="example"><pre>
L =  ["I","like","Erlang"],
Sum = 0,
while( L != []){
    Sum += length(head(L)),
    L = tail(L)
end</pre></div>
    

    <h4>mapfoldl</h4>
      
<div class="example"><pre>

mapfoldl(F, Accu0, [Hd|Tail]) -&gt;
    {R,Accu1} = F(Hd, Accu0),
    {Rs,Accu2} = mapfoldl(F, Accu1, Tail),
    {[R|Rs], Accu2};
mapfoldl(F, Accu, []) -&gt; {[], Accu}.</pre></div>      <p><span class="code">mapfoldl</span> simultaneously maps and folds over a list.
        The following example shows how to change all letters in
        <span class="code">L</span> to upper case and count them.</p>
      <p>First upcase:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">Upcase =  fun(X) when $a =&lt; X,  X =&lt; $z -&gt; X + $A - $a;</span>
<span class="bold_code">(X) -&gt; X</span> 
<span class="bold_code">end.</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">Upcase_word =</span> 
<span class="bold_code">fun(X) -&gt;</span> 
<span class="bold_code">lists:map(Upcase, X)</span> 
<span class="bold_code">end.</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">Upcase_word("Erlang").</span>
"ERLANG"
&gt; <span class="bold_code">lists:map(Upcase_word, L).</span>
["I","LIKE","ERLANG"]</pre></div>
      <p>Now we can do the fold and the map at the same time:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:mapfoldl(fun(Word, Sum) -&gt;</span>
<span class="bold_code">{Upcase_word(Word), Sum + length(Word)}</span>
<span class="bold_code">end, 0, L).</span>
{["I","LIKE","ERLANG"],11}</pre></div>
    

    <h4>filter</h4>
      
<div class="example"><pre>

filter(F, [H|T]) -&gt;
    case F(H) of
        true  -&gt; [H|filter(F, T)];
        false -&gt; filter(F, T)
    end;
filter(F, []) -&gt; [].</pre></div>      <p><span class="code">filter</span> takes a predicate of one argument and a list
        and returns all element in the list which satisfy
        the predicate.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:filter(Big, [500,12,2,45,6,7]).</span>
[500,12,45]</pre></div>
      <p>When we combine maps and filters we can write very succinct
        code. For example, suppose we want to define a set difference
        function. We want to define <span class="code">diff(L1, L2)</span> to be
        the difference between the lists <span class="code">L1</span> and <span class="code">L2</span>.
        This is the list of all elements in L1 which are not contained
        in L2. This code can be written as follows:</p>
      <div class="example"><pre>
diff(L1, L2) -&gt; 
    filter(fun(X) -&gt; not member(X, L2) end, L1).</pre></div>
      <p>The AND intersection of the list <span class="code">L1</span> and <span class="code">L2</span> is
        also easily defined:</p>
      <div class="example"><pre>
intersection(L1,L2) -&gt; filter(fun(X) -&gt; member(X,L1) end, L2).</pre></div>
    

    <h4>takewhile</h4>
      
<div class="example"><pre>

takewhile(Pred, [H|T]) -&gt;
    case Pred(H) of
        true  -&gt; [H|takewhile(Pred, T)];
        false -&gt; []
    end;
takewhile(Pred, []) -&gt;
    [].</pre></div>      <p><span class="code">takewhile(P, L)</span> takes elements <span class="code">X</span> from a list
        <span class="code">L</span> as long as the predicate <span class="code">P(X)</span> is true.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:takewhile(Big, [200,500,45,5,3,45,6]).</span>  
[200,500,45]</pre></div>
    

    <h4>dropwhile</h4>
      
<div class="example"><pre>

dropwhile(Pred, [H|T]) -&gt;
    case Pred(H) of
        true  -&gt; dropwhile(Pred, T);
        false -&gt; [H|T]
    end;
dropwhile(Pred, []) -&gt;
    [].</pre></div>      <p><span class="code">dropwhile</span> is the complement of <span class="code">takewhile</span>.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:dropwhile(Big, [200,500,45,5,3,45,6]).</span>
[5,3,45,6]</pre></div>
    

    <h4>splitwith</h4>
      
<div class="example"><pre>

splitwith(Pred, L) -&gt;
    splitwith(Pred, L, []).

splitwith(Pred, [H|T], L) -&gt;
    case Pred(H) of 
        true  -&gt; splitwith(Pred, T, [H|L]);
        false -&gt; {reverse(L), [H|T]}
    end;
splitwith(Pred, [], L) -&gt;
    {reverse(L), []}.</pre></div>      <p><span class="code">splitwith(P, L)</span> splits the list <span class="code">L</span> into the two
        sub-lists <span class="code">{L1, L2}</span>, where <span class="code">L = takewhile(P, L)</span>
        and <span class="code">L2 = dropwhile(P, L)</span>.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">lists:splitwith(Big, [200,500,45,5,3,45,6]).</span>
{[200,500,45],[5,3,45,6]}</pre></div>
    
  

  <h3><a name="id62549">2.6 
        Funs Which Return Funs</a></h3>
    
    <p>So far, this section has only described functions which take
      funs as arguments. It is also possible to write more powerful
      functions which themselves return funs. The following examples
      illustrate these type of functions.</p>

    <h4>Simple Higher Order Functions</h4>
      
      <p><span class="code">Adder(X)</span> is a function which, given <span class="code">X</span>, returns
        a new function <span class="code">G</span> such that <span class="code">G(K)</span> returns
        <span class="code">K + X</span>.</p>
      <div class="example"><pre>
&gt; <span class="bold_code">Adder = fun(X) -&gt; fun(Y) -&gt; X + Y end end.</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">Add6 = Adder(6).</span>
#Fun&lt;erl_eval.6.72228031&gt;
&gt; <span class="bold_code">Add6(10).</span>
16</pre></div>
    

    <h4>Infinite Lists</h4>
      
      <p>The idea is to write something like:</p>
      <div class="example"><pre>
-module(lazy).
-export([ints_from/1]).
ints_from(N) -&gt;
    fun() -&gt;
            [N|ints_from(N+1)]
    end.</pre></div>
      <p>Then we can proceed as follows:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">XX = lazy:ints_from(1).</span>
#Fun&lt;lazy.0.29874839&gt;
&gt; <span class="bold_code">XX().</span>
[1|#Fun&lt;lazy.0.29874839&gt;]
&gt; <span class="bold_code">hd(XX()).</span>
1
&gt; <span class="bold_code">Y = tl(XX()).</span>
#Fun&lt;lazy.0.29874839&gt;
&gt; <span class="bold_code">hd(Y()).</span>
2</pre></div>
      <p>etc. - this is an example of "lazy embedding".</p>
    

    <h4>Parsing</h4>
      
      <p>The following examples show parsers of the following type:</p>
      <div class="example"><pre>
Parser(Toks) -&gt; {ok, Tree, Toks1} | fail</pre></div>
      <p><span class="code">Toks</span> is the list of tokens to be parsed. A successful
        parse returns <span class="code">{ok, Tree, Toks1}</span>, where <span class="code">Tree</span> is a
        parse tree and <span class="code">Toks1</span> is a tail of <span class="code">Tree</span> which
        contains symbols encountered after the structure which was
        correctly parsed. Otherwise <span class="code">fail</span> is returned.</p>
      <p>The example which follows illustrates a simple, functional
        parser which parses the grammar:</p>
      <div class="example"><pre>
(a | b) &amp; (c | d)</pre></div>
      <p>The following code defines a function <span class="code">pconst(X)</span> in
        the module <span class="code">funparse</span>, which returns a fun which parses a
        list of tokens.</p>
<div class="example"><pre>

pconst(X) -&gt;
    fun (T) -&gt;
       case T of
           [X|T1] -&gt; {ok, {const, X}, T1};
           _      -&gt; fail
       end
    end.</pre></div>      <p>This function can be used as follows:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">P1 = funparse:pconst(a).</span>
#Fun&lt;funparse.0.22674075&gt;
&gt; <span class="bold_code">P1([a,b,c]).</span>
{ok,{const,a},[b,c]}
&gt; <span class="bold_code">P1([x,y,z]).</span>     
fail</pre></div>
      <p>Next, we define the two higher order functions <span class="code">pand</span>
        and <span class="code">por</span> which combine primitive parsers to produce more
        complex parsers. Firstly <span class="code">pand</span>:</p>
<div class="example"><pre>

pand(P1, P2) -&gt;
    fun (T) -&gt;
        case P1(T) of
            {ok, R1, T1} -&gt;
                case P2(T1) of
                    {ok, R2, T2} -&gt;
                        {ok, {'and', R1, R2}};
                    fail -&gt;
                        fail
                end;
            fail -&gt;
                fail
        end
    end.</pre></div>      <p>Given a parser <span class="code">P1</span> for grammar <span class="code">G1</span>, and a parser
        <span class="code">P2</span> for grammar <span class="code">G2</span>, <span class="code">pand(P1, P2)</span> returns a
        parser for the grammar which consists of sequences of tokens
        which satisfy <span class="code">G1</span> followed by sequences of tokens which
        satisfy <span class="code">G2</span>.</p>
      <p><span class="code">por(P1, P2)</span> returns a parser for the language
        described by the grammar <span class="code">G1</span> or <span class="code">G2</span>.</p>
<div class="example"><pre>

por(P1, P2) -&gt;
    fun (T) -&gt;
        case P1(T) of
            {ok, R, T1} -&gt; 
                {ok, {'or',1,R}, T1};
            fail -&gt; 
                case P2(T) of
                    {ok, R1, T1} -&gt;
                        {ok, {'or',2,R1}, T1};
                    fail -&gt;
                        fail
                end
        end
    end.</pre></div>      <p>The original problem was to parse the grammar
        <span class="code">(a | b) &amp; (c | d)</span>. The following code addresses this
        problem:</p>
<div class="example"><pre>

grammar() -&gt;
    pand(
         por(pconst(a), pconst(b)),
         por(pconst(c), pconst(d))).</pre></div>      <p>The following code adds a parser interface to the grammar:</p>
<div class="example"><pre>

parse(List) -&gt;
    (grammar())(List).</pre></div>      <p>We can test this parser as follows:</p>
      <div class="example"><pre>
&gt; <span class="bold_code">funparse:parse([a,c]).</span>
{ok,{'and',{'or',1,{const,a}},{'or',1,{const,c}}}}
&gt; <span class="bold_code">funparse:parse([a,d]).</span> 
{ok,{'and',{'or',1,{const,a}},{'or',2,{const,d}}}}
&gt; <span class="bold_code">funparse:parse([b,c]).</span>   
{ok,{'and',{'or',2,{const,b}},{'or',1,{const,c}}}}
&gt; <span class="bold_code">funparse:parse([b,d]).</span> 
{ok,{'and',{'or',2,{const,b}},{'or',2,{const,d}}}}
&gt; <span class="bold_code">funparse:parse([a,b]).</span>   
fail</pre></div>
    
  
</div>
<div class="footer">
<hr>
<p>Copyright © 2003-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>