Erlang的普通函数和匿名函数fun:
范例1:以下函数列出商品的价格。该函数包含5个子句,各个子句之间由分号;分隔。
要在函数所在模块之外使用该函数,应该在-export中导出改函数。
-module(shop).
-export([cost/1]).
cost(oranges) -> 5;
cost(newspaper) -> 8;
cost(apples) -> 2;
cost(pears) -> 9;
cost(milk) -> 7.
范例2:以下函数计算购物清单的商品总价格。
-module(shop1).
-export([total/1]).
total([{What,N}|T]) ->
shop:cost(What)*N + total(T);
total([]) ->
0.
执行:
1>Buy=[{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}].
2>total(Buy).
范例3:同名不同目的函数,以下是两个不同的函数。
sum(L) -> sum(L,0).
sum([],N) -> N;
sum([H|T],N) ->sum(T,H+N).
fun 匿名函数
fun既可以做函数的参数,也可以做函数(或fun)的结果。
这样的函数分别叫:以fun为参数的函数,返回fun的函数。
以fun为参数的函数:
例:
1>Double= fun(X) -> 2 * X end.
2>L = [1,2,3,4].
3>lists:map(Double,L). 返回结果:[2,4,6,8]
4>Even = fun(X) -> (X rem 2) =:= 0 end. (=:= 是恒等符号)
5>lists:filter(Even,L). 返回结果:[2,4]
6>lists:map(Even,L). 返回结果:[false,true,false,true]
lists:map(F,L) 将fun F应用到列表L的每个元素上,并返回一个新的列表。
lists:filter(P,L). 返回一个新列表,新列表的每个元素由L中每一个能满足P(E)为true的元素组成。
像map,filter这样的函数,在一个函数调用中处理整个列表的操作,使程序变得简洁易懂。
返回fun的函数:
例:
1>Fruit = [apple,pear,orange].
2>MakeTest = fun(L) -> (fun(X) -> lists:member(X,L) end) end.
3>IsFruit = MakeTest(Fruit). 【MakeTest返回的是一个函数】
4>IsFruit(apple).
true
5>IsFruit(dog).
false
6>lists:filter(IsFruit,[orange,apple,dog,cat,bear]).
简单列表处理:
-module(mylists).
-export([sum/1,
map/2]).
%%这两个是标准库lists模块中map函数的定义
sum([]) -> 0;
sum([H|T]) -> H + sum(T).
map(_,[]) -> [];
map(F,[H|T]) -> [F(H)|map(F,T)].
有了sum和map这两个函数,就可以对上面的total函数做下改进了:
-module(shop2).
-export([total/1]).
-import(lists,[map/2,sum/1]).
total(L) ->
sum(map(fun({What,N})->shop:cost(What)*N end,L)).