2、高階函數 fun 2.1 樣本 1 :映射 map map(F, [H|T]) -> [F(H)|map(F, T)];map(F, []) -> [].double(L) -> map(fun(X) -> 2*X end, L).add_one(L) -> map(fun(X) -> 1 + X end, L).2.2 樣本 2 :迴圈 foreachforeach(F, [H|T]) -> F(H), foreach(F, T);foreach(F, []) -> ok.print_list(L) -> foreach(fun(H) -> io:format(S, "~p~n",[H]) end, L).broadcast(L) -> foreach(fun(Pid) -> Pid ! M end, L).2.3 高階函數文法F = fun (Arg1, Arg2, ... ArgN) -> ... end文法1:同一模組中,把函數作為參數值傳遞F = fun FunctionName/Arity文法2:不同模組中,定義函數F = {Module, FunctionName}建立函數的不同方式:-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.函數求值的文法:F(Arg1, Arg2, ..., Argn)f(F, Args) when is_function(F) -> apply(F, Args);f(N, _) when is_integer(N) -> N.高階函數是獨特類型。有內建函數對其管理:erlang:fun_info/1,2 查看fun的資訊erlang:fun_to_list/1 返回fun的文本運算式erlang:check_process_code/2 如果進程內的funs相依模組早期版本,返回true2.4 高階函數內部對變數的約束(1) 出現在fun頭部的變數,是未約束值的("fresh" variable);(2) 變數定義在fun之前,並且出現在函數調用中,或者出現在fun的guard測試中的,其值約束於fun的外部;(3) fun中的變數不可匯出。print_list(File, List) -> {ok, Stream} = file:open(File, write), foreach(fun(X) -> io:format(Stream,"~p~n",[X]) end, List), file:close(Stream).X是未經約束的新變數,Stream源於file:open。把變數匯入fun時,要受限制:有些模式比對的操作,要放入guard運算式,並且不可寫入fun的頭部。這是正確的:f(...) -> Y = ... map(fun(X) when X == Y -> ; (_) -> ... end, ...) ...下面是錯誤的:f(...) -> Y = ... map(fun(Y) -> ; (_) -> ... end, ...) ...2.5 高階函數和模組listsFuns and the Module ListsThe following examples show a dialogue with the Erlang shell. All the higher order functions discussed are exported from the module lists. 2.5.1 mapmap(F, [H|T]) -> [F(H)|map(F, T)];map(F, []) -> [].> Double = fun(X) -> 2 * X end.#Fun<erl_eval.6.72228031>> lists:map(Double, [1,2,3,4,5]).[2,4,6,8,10]2.5.2 anyany(Pred, [H|T]) -> case Pred(H) of true -> true; false -> any(Pred, T) end;any(Pred, []) -> false.> Big = fun(X) -> if X > 10 -> true; true -> false end end.#Fun<erl_eval.6.72228031>> lists:any(Big, [1,2,3,4]).false> lists:any(Big, [1,2,3,12,5]).true2.5.3 allall(Pred, [H|T]) -> case Pred(H) of true -> all(Pred, T); false -> false end;all(Pred, []) -> true.all has the same arguments as any. It is true if the predicate applied to all elements in the list is true. > lists:all(Big, [1,2,3,4,12,6]).false> lists:all(Big, [12,13,14,15]).true2.5.4 foreachforeach(F, [H|T]) -> F(H), foreach(F, T);foreach(F, []) -> ok.> lists:foreach(fun(X) -> io:format("~w~n",[X]) end, [1,2,3,4]).1234ok2.5.5 foldlfoldl(F, Accu, [Hd|Tail]) -> foldl(F, F(Hd, Accu), Tail);foldl(F, Accu, []) -> Accu.> L = ["I","like","Erlang"].["I","like","Erlang"]10> lists:foldl(fun(X, Sum) -> length(X) + Sum end, 0, L).11foldl works like a while loop in an imperative language: L = ["I","like","Erlang"],Sum = 0,while( L != []){ Sum += length(head(L)), L = tail(L)end2.5.6 mapfoldlmapfoldl(F, Accu0, [Hd|Tail]) -> {R,Accu1} = F(Hd, Accu0), {Rs,Accu2} = mapfoldl(F, Accu1, Tail), {[R|Rs], Accu2};mapfoldl(F, Accu, []) -> {[], Accu}.> Upcase = fun(X) when $a =< X, X =< $z -> X + $A - $a;(X) -> Xend.#Fun<erl_eval.6.72228031>> Upcase_word =fun(X) ->lists:map(Upcase, X)end.#Fun<erl_eval.6.72228031>> Upcase_word("Erlang")."ERLANG"> lists:map(Upcase_word, L).["I","LIKE","ERLANG"]Now we can do the fold and the map at the same time: > lists:mapfoldl(fun(Word, Sum) ->{Upcase_word(Word), Sum + length(Word)}end, 0, L).{["I","LIKE","ERLANG"],11}2.5.7 filterfilter(F, [H|T]) -> case F(H) of true -> [H|filter(F, T)]; false -> filter(F, T) end;filter(F, []) -> [].> lists:filter(Big, [500,12,2,45,6,7]).[500,12,45]diff(L1, L2) -> filter(fun(X) -> not member(X, L2) end, L1).intersection(L1,L2) -> filter(fun(X) -> member(X,L1) end, L2).2.5.8 takewhiletakewhile(Pred, [H|T]) -> case Pred(H) of true -> [H|takewhile(Pred, T)]; false -> [] end;takewhile(Pred, []) -> [].> lists:takewhile(Big, [200,500,45,5,3,45,6]).[200,500,45]2.5.9 dropwhiledropwhile(Pred, [H|T]) -> case Pred(H) of true -> dropwhile(Pred, T); false -> [H|T] end;dropwhile(Pred, []) -> [].> lists:dropwhile(Big, [200,500,45,5,3,45,6]).[5,3,45,6]2.5.10 splitwithsplitwith(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), []}.> lists:splitwith(Big, [200,500,45,5,3,45,6]).{[200,500,45],[5,3,45,6]}2.6 函數返回的值也是函數Funs Which Return FunsSo 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. 2.6.1 簡單的高階函數> Adder = fun(X) -> fun(Y) -> X + Y end end.#Fun<erl_eval.6.72228031>> Add6 = Adder(6).#Fun<erl_eval.6.72228031>> Add6(10).162.6.2 無限列表-module(lazy).-export([ints_from/1]).ints_from(N) -> fun() -> [N|ints_from(N+1)] end.> XX = lazy:ints_from(1).#Fun<lazy.0.29874839>> XX().[1|#Fun<lazy.0.29874839>]> hd(XX()).1> Y = tl(XX()).#Fun<lazy.0.29874839>> hd(Y()).22.6.3 解析演算法(Parsing)解析函數:Parser(Toks) -> {ok, Tree, Toks1} | failToke是解析對象(符號)的列表。Tree是解析樹,Toks1是樹的尾節點。解析失敗返回fail。要解析的文法:(a | b) & (c | d)pconst(X) -> fun (T) -> case T of [X|T1] -> {ok, {const, X}, T1}; _ -> fail end end.This function can be used as follows: > P1 = funparse:pconst(a).#Fun<funparse.0.22674075>> P1([a,b,c]).{ok,{const,a},[b,c]}> P1([x,y,z]).failNext, we define the two higher order functions pand and por which combine primitive parsers to produce more complex parsers. Firstly pand: 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.Given a parser P1 for grammar G1, and a parser P2 for grammar G2, pand(P1, P2) returns a parser for the grammar which consists of sequences of tokens which satisfy G1 followed by sequences of tokens which satisfy G2. por(P1, P2) returns a parser for the language described by the grammar G1 or G2. 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.The original problem was to parse the grammar (a | b) & (c | d). The following code addresses this problem: grammar() -> pand( por(pconst(a), pconst(b)), por(pconst(c), pconst(d))).The following code adds a parser interface to the grammar: parse(List) -> (grammar())(List).We can test this parser as follows: > funparse:parse([a,c]).{ok,{'and',{'or',1,{const,a}},{'or',1,{const,c}}}}> funparse:parse([a,d]).{ok,{'and',{'or',1,{const,a}},{'or',2,{const,d}}}}> funparse:parse([b,c]).{ok,{'and',{'or',2,{const,b}},{'or',1,{const,c}}}}> funparse:parse([b,d]).{ok,{'and',{'or',2,{const,b}},{'or',2,{const,d}}}}> funparse:parse([a,b]).fail