1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
<TITLE>Funs</TITLE>
<SCRIPT type="text/javascript" src="../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="2"><!-- Empty --></A>
<H2>2 Funs</H2>
<A NAME="2.1"><!-- Empty --></A>
<H3>2.1 Example 1 - map</H3>
<P>If we want to double every element in a list, we could write a
function named <CODE>double</CODE>:
<PRE>
double([H|T]) -> [2*H|double(T)];
double([]) -> [].
</PRE>
<P>This function obviously doubles the argument entered as input
as follows:
<PRE>
> <STRONG>double([1,2,3,4]).</STRONG>
[2,4,6,8]
</PRE>
<P>We now add the function <CODE>add_one</CODE>, which adds one to every
element in a list:
<PRE>
add_one([H|T]) -> [H+1|add_one(T)];
add_one([]) -> [].
</PRE>
<P>These functions, <CODE>double</CODE> and <CODE>add_one</CODE>, have a very
similar structure. We can exploit this fact and write a function
<CODE>map</CODE> which expresses this similarity:
<PRE>
map(F, [H|T]) -> [F(H)|map(F, T)];
map(F, []) -> [].
</PRE>
<P>We can now express the functions <CODE>double</CODE> and
<CODE>add_one</CODE> in terms of <CODE>map</CODE> as follows:
<PRE>
double(L) -> map(fun(X) -> 2*X end, L).
add_one(L) -> map(fun(X) -> 1 + X end, L).
</PRE>
<P><CODE>map(F, List)</CODE> is a function which takes a function
<CODE>F</CODE> and a list <CODE>L</CODE> as arguments and returns the new
list which is obtained by applying <CODE>F</CODE> to each of
the elements in <CODE>L</CODE>.
<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>
<OL>
<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>
</OL>
<A NAME="2.2"><!-- Empty --></A>
<H3>2.2 Example 2 - foreach</H3>
<P>This example illustrates procedural abstraction. Initially, we
show the following two examples written as conventional
functions:
<P>
<OL>
<LI>
all elements of a list are printed onto a stream
</LI>
<LI>
a message is broadcast to a list of processes.
</LI>
</OL>
<PRE>
print_list(Stream, [H|T]) ->
io:format(Stream, "~p~n", [H]),
print_list(Stream, T);
print_list(Stream, []) ->
true.
</PRE>
<PRE>
broadcast(Msg, [Pid|Pids]) ->
Pid ! Msg,
broadcast(Msg, Pids);
broadcast(_, []) ->
true.
</PRE>
<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>The function <CODE>foreach</CODE> expresses this similarity:
<PRE>
foreach(F, [H|T]) ->
F(H),
foreach(F, T);
foreach(F, []) ->
ok.
</PRE>
<P>Using <CODE>foreach</CODE>, <CODE>print_list</CODE> becomes:
<PRE>
foreach(fun(H) -> io:format(S, "~p~n",[H]) end, L)
</PRE>
<P><CODE>broadcast</CODE> becomes:
<PRE>
foreach(fun(Pid) -> Pid ! M end, L)
</PRE>
<P><CODE>foreach</CODE> is evaluated for its side-effect and not its
value. <CODE>foreach(Fun ,L)</CODE> calls <CODE>Fun(X)</CODE> for each
element <CODE>X</CODE> in <CODE>L</CODE> and the processing occurs in
the order in which the elements were defined in <CODE>L</CODE>.
<CODE>map</CODE> does not define the order in which its elements are
processed.<A NAME="2.3"><!-- Empty --></A>
<H3>2.3 The Syntax of Funs</H3>
<P>Funs are written with the syntax:
<PRE>
F = fun (Arg1, Arg2, ... ArgN) ->
...
end
</PRE>
<P>This creates an anonymous function of <CODE>N</CODE> arguments and
binds it to the variable <CODE>F</CODE>.
<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:
<PRE>
F = fun FunctionName/Arity
</PRE>
<P>With this form of function reference, the function which is
referred to does not need to be exported from the module.
<P>We can also refer to a function defined in a different module
with the following syntax:
<PRE>
F = {Module, FunctionName}
</PRE>
<P>In this case, the function must be exported from the module in
question.
<P>The follow program illustrates the different ways of creating
funs:
<PRE>
-module(fun_test).
-export([t1/0, t2/0, t3/0, t4/0, double/1]).
-import(lists, [map/2]).
t1() -> map(fun(X) -> 2 * X end, [1,2,3,4,5]).
t2() -> map(fun double/1, [1,2,3,4,5]).
t3() -> map({?MODULE, double}, [1,2,3,4,5]).
double(X) -> X * 2.
</PRE>
<P>We can evaluate the fun <CODE>F</CODE> with the syntax:
<PRE>
F(Arg1, Arg2, ..., Argn)
</PRE>
<P>To check whether a term is a fun, use the test
<CODE>is_function/1</CODE> in a guard. Example:
<PRE>
f(F, Args) when is_function(F) ->
apply(F, Args);
f(N, _) when is_integer(N) ->
N.
</PRE>
<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>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P>In OTP R5 and earlier releases, funs were represented using
tuples. </TD>
</TR>
</TABLE>
<A NAME="2.4"><!-- Empty --></A>
<H3>2.4 Variable Bindings Within a Fun</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:
<PRE>
print_list(File, List) ->
{ok, Stream} = file:open(File, write),
foreach(fun(X) -> io:format(Stream,"~p~n",[X]) end, List),
file:close(Stream).
</PRE>
<P>In the above example, the variable <CODE>X</CODE> which is defined in
the head of the fun is a new variable. The value of the variable
<CODE>Stream</CODE> which is used within within the fun gets its value
from the <CODE>file:open</CODE> line.
<P>Since any variable which occurs in the head of a fun is
considered a new variable it would be equally valid to write:
<PRE>
print_list(File, List) ->
{ok, Stream} = file:open(File, write),
foreach(fun(File) ->
io:format(Stream,"~p~n",[File])
end, List),
file:close(Stream).
</PRE>
<P>In this example, <CODE>File</CODE> is used as the new variable
instead of <CODE>X</CODE>. This is rather silly since code in the body
of the fun cannot refer to the variable <CODE>File</CODE> which is
defined outside the fun. Compiling this example will yield
the diagnostic:
<PRE>
./FileName.erl:Line: Warning: variable 'File'
shadowed in 'lambda head'
</PRE>
<P>This reminds us that the variable <CODE>File</CODE> which is defined
inside the fun collides with the variable <CODE>File</CODE> which is
defined outside the fun.
<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 <CODE>F</CODE> to be evaluated when the value of
its argument is <CODE>Y</CODE>:
<PRE>
f(...) ->
Y = ...
map(fun(X) when X == Y ->
;
(_) ->
...
end, ...)
...
</PRE>
<P>instead of
<PRE>
f(...) ->
Y = ...
map(fun(Y) ->
;
(_) ->
...
end, ...)
...
</PRE>
<A NAME="2.5"><!-- Empty --></A>
<H3>2.5 Funs and the Module Lists</H3>
<P>The following examples show a dialogue with the Erlang shell.
All the higher order functions discussed are exported from
the module <CODE>lists</CODE>.<A NAME="2.5.1"><!-- Empty --></A>
<H4>2.5.1 map</H4>
<PRE>
map(F, [H|T]) -> [F(H)|map(F, T)];
map(F, []) -> [].
</PRE>
<P><CODE>map</CODE> 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.
<PRE>
> <STRONG>Double = fun(X) -> 2 * X end.</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>lists:map(Double, [1,2,3,4,5]).</STRONG>
[2,4,6,8,10]
</PRE>
<P>When a new fun is defined in the shell, the value of the Fun
is printed as <CODE>Fun#<erl_eval></CODE>.<A NAME="2.5.2"><!-- Empty --></A>
<H4>2.5.2 any</H4>
<PRE>
any(Pred, [H|T]) ->
case Pred(H) of
true -> true;
false -> any(Pred, T)
end;
any(Pred, []) ->
false.
</PRE>
<P><CODE>any</CODE> takes a predicate <CODE>P</CODE> of one argument and a
list of terms. A predicate is a function which returns
<CODE>true</CODE> or <CODE>false</CODE>. <CODE>any</CODE> is true if there is a
term <CODE>X</CODE> in the list such that <CODE>P(X)</CODE> is <CODE>true</CODE>.
<P>We define a predicate <CODE>Big(X)</CODE> which is <CODE>true</CODE> if
its argument is greater that 10.
<PRE>
> <STRONG>Big = fun(X) -> if X > 10 -> true; true -> false end end.</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>lists:any(Big, [1,2,3,4]).</STRONG>
false
> <STRONG>lists:any(Big, [1,2,3,12,5]).</STRONG>
true
</PRE>
<A NAME="2.5.3"><!-- Empty --></A>
<H4>2.5.3 all</H4>
<PRE>
all(Pred, [H|T]) ->
case Pred(H) of
true -> all(Pred, T);
false -> false
end;
all(Pred, []) ->
true.
</PRE>
<P><CODE>all</CODE> has the same arguments as <CODE>any</CODE>. It is true
if the predicate applied to all elements in the list is true.
<PRE>
> <STRONG>lists:all(Big, [1,2,3,4,12,6]).</STRONG>
false
> <STRONG>lists:all(Big, [12,13,14,15]).</STRONG>
true
</PRE>
<A NAME="2.5.4"><!-- Empty --></A>
<H4>2.5.4 foreach</H4>
<PRE>
foreach(F, [H|T]) ->
F(H),
foreach(F, T);
foreach(F, []) ->
ok.
</PRE>
<P><CODE>foreach</CODE> takes a function of one argument and a list of
terms. The function is applied to each argument in the list.
<CODE>foreach</CODE> returns <CODE>ok</CODE>. It is used for its
side-effect only.
<PRE>
> <STRONG>lists:foreach(fun(X) -> io:format("~w~n",[X]) end, [1,2,3,4]).</STRONG>
1
2
3
4
ok
</PRE>
<A NAME="2.5.5"><!-- Empty --></A>
<H4>2.5.5 foldl</H4>
<PRE>
foldl(F, Accu, [Hd|Tail]) ->
foldl(F, F(Hd, Accu), Tail);
foldl(F, Accu, []) -> Accu.
</PRE>
<P><CODE>foldl</CODE> 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>If we have a list of lists <CODE>L = ["I","like","Erlang"]</CODE>,
then we can sum the lengths of all the strings in <CODE>L</CODE> as
follows:
<PRE>
> <STRONG>L = ["I","like","Erlang"].</STRONG>
["I","like","Erlang"]
10> <STRONG>lists:foldl(fun(X, Sum) -> length(X) + Sum end, 0, L).</STRONG>
11
</PRE>
<P><CODE>foldl</CODE> works like a <CODE>while</CODE> loop in an imperative
language:
<PRE>
L = ["I","like","Erlang"],
Sum = 0,
while( L != []){
Sum += length(head(L)),
L = tail(L)
end
</PRE>
<A NAME="2.5.6"><!-- Empty --></A>
<H4>2.5.6 mapfoldl</H4>
<PRE>
mapfoldl(F, Accu0, [Hd|Tail]) ->
{R,Accu1} = F(Hd, Accu0),
{Rs,Accu2} = mapfoldl(F, Accu1, Tail),
{[R|Rs], Accu2};
mapfoldl(F, Accu, []) -> {[], Accu}.
</PRE>
<P><CODE>mapfoldl</CODE> simultaneously maps and folds over a list.
The following example shows how to change all letters in
<CODE>L</CODE> to upper case and count them.
<P>First upcase:
<PRE>
> <STRONG>Upcase = fun(X) when $a =< X, X =< $z -> X + $A - $a;</STRONG>
<STRONG>(X) -> X</STRONG>
<STRONG>end.</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>Upcase_word =</STRONG>
<STRONG>fun(X) -></STRONG>
<STRONG>lists:map(Upcase, X)</STRONG>
<STRONG>end.</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>Upcase_word("Erlang").</STRONG>
"ERLANG"
> <STRONG>lists:map(Upcase_word, L).</STRONG>
["I","LIKE","ERLANG"]
</PRE>
<P>Now we can do the fold and the map at the same time:
<PRE>
> <STRONG>lists:mapfoldl(fun(Word, Sum) -></STRONG>
<STRONG>{Upcase_word(Word), Sum + length(Word)}</STRONG>
<STRONG>end, 0, L).</STRONG>
{["I","LIKE","ERLANG"],11}
</PRE>
<A NAME="2.5.7"><!-- Empty --></A>
<H4>2.5.7 filter</H4>
<PRE>
filter(F, [H|T]) ->
case F(H) of
true -> [H|filter(F, T)];
false -> filter(F, T)
end;
filter(F, []) -> [].
</PRE>
<P><CODE>filter</CODE> takes a predicate of one argument and a list
and returns all element in the list which satisfy
the predicate.
<PRE>
> <STRONG>lists:filter(Big, [500,12,2,45,6,7]).</STRONG>
[500,12,45]
</PRE>
<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 <CODE>diff(L1, L2)</CODE> to be
the difference between the lists <CODE>L1</CODE> and <CODE>L2</CODE>.
This is the list of all elements in L1 which are not contained
in L2. This code can be written as follows:
<PRE>
diff(L1, L2) ->
filter(fun(X) -> not member(X, L2) end, L1).
</PRE>
<P>The AND intersection of the list <CODE>L1</CODE> and <CODE>L2</CODE> is
also easily defined:
<PRE>
intersection(L1,L2) -> filter(fun(X) -> member(X,L1) end, L2).
</PRE>
<A NAME="2.5.8"><!-- Empty --></A>
<H4>2.5.8 takewhile</H4>
<PRE>
takewhile(Pred, [H|T]) ->
case Pred(H) of
true -> [H|takewhile(Pred, T)];
false -> []
end;
takewhile(Pred, []) ->
[].
</PRE>
<P><CODE>takewhile(P, L)</CODE> takes elements <CODE>X</CODE> from a list
<CODE>L</CODE> as long as the predicate <CODE>P(X)</CODE> is true.
<PRE>
> <STRONG>lists:takewhile(Big, [200,500,45,5,3,45,6]).</STRONG>
[200,500,45]
</PRE>
<A NAME="2.5.9"><!-- Empty --></A>
<H4>2.5.9 dropwhile</H4>
<PRE>
dropwhile(Pred, [H|T]) ->
case Pred(H) of
true -> dropwhile(Pred, T);
false -> [H|T]
end;
dropwhile(Pred, []) ->
[].
</PRE>
<P><CODE>dropwhile</CODE> is the complement of <CODE>takewhile</CODE>.
<PRE>
> <STRONG>lists:dropwhile(Big, [200,500,45,5,3,45,6]).</STRONG>
[5,3,45,6]
</PRE>
<A NAME="2.5.10"><!-- Empty --></A>
<H4>2.5.10 splitwith</H4>
<PRE>
splitwith(Pred, L) ->
splitwith(Pred, L, []).
splitwith(Pred, [H|T], L) ->
case Pred(H) of
true -> splitwith(Pred, T, [H|L]);
false -> {reverse(L), [H|T]}
end;
splitwith(Pred, [], L) ->
{reverse(L), []}.
</PRE>
<P><CODE>splitwith(P, L)</CODE> splits the list <CODE>L</CODE> into the two
sub-lists <CODE>{L1, L2}</CODE>, where <CODE>L = takewhile(P, L)</CODE>
and <CODE>L2 = dropwhile(P, L)</CODE>.
<PRE>
> <STRONG>lists:splitwith(Big, [200,500,45,5,3,45,6]).</STRONG>
{[200,500,45],[5,3,45,6]}
</PRE>
<A NAME="2.6"><!-- Empty --></A>
<H3>2.6 Funs Which Return Funs</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.<A NAME="2.6.1"><!-- Empty --></A>
<H4>2.6.1 Simple Higher Order Functions</H4>
<P><CODE>Adder(X)</CODE> is a function which, given <CODE>X</CODE>, returns
a new function <CODE>G</CODE> such that <CODE>G(K)</CODE> returns
<CODE>K + X</CODE>.
<PRE>
> <STRONG>Adder = fun(X) -> fun(Y) -> X + Y end end.</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>Add6 = Adder(6).</STRONG>
#Fun<erl_eval.6.72228031>
> <STRONG>Add6(10).</STRONG>
16
</PRE>
<A NAME="2.6.2"><!-- Empty --></A>
<H4>2.6.2 Infinite Lists</H4>
<P>The idea is to write something like:
<PRE>
-module(lazy).
-export([ints_from/1]).
ints_from(N) ->
fun() ->
[N|ints_from(N+1)]
end.
</PRE>
<P>Then we can proceed as follows:
<PRE>
> <STRONG>XX = lazy:ints_from(1).</STRONG>
#Fun<lazy.0.29874839>
> <STRONG>XX().</STRONG>
[1|#Fun<lazy.0.29874839>]
> <STRONG>hd(XX()).</STRONG>
1
> <STRONG>Y = tl(XX()).</STRONG>
#Fun<lazy.0.29874839>
> <STRONG>hd(Y()).</STRONG>
2
</PRE>
<P>etc. - this is an example of "lazy embedding".<A NAME="2.6.3"><!-- Empty --></A>
<H4>2.6.3 Parsing</H4>
<P>The following examples show parsers of the following type:
<PRE>
Parser(Toks) -> {ok, Tree, Toks1} | fail
</PRE>
<P><CODE>Toks</CODE> is the list of tokens to be parsed. A successful
parse returns <CODE>{ok, Tree, Toks1}</CODE>, where <CODE>Tree</CODE> is a
parse tree and <CODE>Toks1</CODE> is a tail of <CODE>Tree</CODE> which
contains symbols encountered after the structure which was
correctly parsed. Otherwise <CODE>fail</CODE> is returned.
<P>The example which follows illustrates a simple, functional
parser which parses the grammar:
<PRE>
(a | b) & (c | d)
</PRE>
<P>The following code defines a function <CODE>pconst(X)</CODE> in
the module <CODE>funparse</CODE>, which returns a fun which parses a
list of tokens.
<PRE>
pconst(X) ->
fun (T) ->
case T of
[X|T1] -> {ok, {const, X}, T1};
_ -> fail
end
end.
</PRE>
<P>This function can be used as follows:
<PRE>
> <STRONG>P1 = funparse:pconst(a).</STRONG>
#Fun<funparse.0.22674075>
> <STRONG>P1([a,b,c]).</STRONG>
{ok,{const,a},[b,c]}
> <STRONG>P1([x,y,z]).</STRONG>
fail
</PRE>
<P>Next, we define the two higher order functions <CODE>pand</CODE>
and <CODE>por</CODE> which combine primitive parsers to produce more
complex parsers. Firstly <CODE>pand</CODE>:
<PRE>
pand(P1, P2) ->
fun (T) ->
case P1(T) of
{ok, R1, T1} ->
case P2(T1) of
{ok, R2, T2} ->
{ok, {'and', R1, R2}};
fail ->
fail
end;
fail ->
fail
end
end.
</PRE>
<P>Given a parser <CODE>P1</CODE> for grammar <CODE>G1</CODE>, and a parser
<CODE>P2</CODE> for grammar <CODE>G2</CODE>, <CODE>pand(P1, P2)</CODE> returns a
parser for the grammar which consists of sequences of tokens
which satisfy <CODE>G1</CODE> followed by sequences of tokens which
satisfy <CODE>G2</CODE>.
<P><CODE>por(P1, P2)</CODE> returns a parser for the language
described by the grammar <CODE>G1</CODE> or <CODE>G2</CODE>.
<PRE>
por(P1, P2) ->
fun (T) ->
case P1(T) of
{ok, R, T1} ->
{ok, {'or',1,R}, T1};
fail ->
case P2(T) of
{ok, R1, T1} ->
{ok, {'or',2,R1}, T1};
fail ->
fail
end
end
end.
</PRE>
<P>The original problem was to parse the grammar
<CODE>(a | b) & (c | d)</CODE>. The following code addresses this
problem:
<PRE>
grammar() ->
pand(
por(pconst(a), pconst(b)),
por(pconst(c), pconst(d))).
</PRE>
<P>The following code adds a parser interface to the grammar:
<PRE>
parse(List) ->
(grammar())(List).
</PRE>
<P>We can test this parser as follows:
<PRE>
> <STRONG>funparse:parse([a,c]).</STRONG>
{ok,{'and',{'or',1,{const,a}},{'or',1,{const,c}}}}
> <STRONG>funparse:parse([a,d]).</STRONG>
{ok,{'and',{'or',1,{const,a}},{'or',2,{const,d}}}}
> <STRONG>funparse:parse([b,c]).</STRONG>
{ok,{'and',{'or',2,{const,b}},{'or',1,{const,c}}}}
> <STRONG>funparse:parse([b,d]).</STRONG>
{ok,{'and',{'or',2,{const,b}},{'or',2,{const,d}}}}
> <STRONG>funparse:parse([a,b]).</STRONG>
fail
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright © 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>
|