函数式参数

函数式参数

将函数名作为参数传递给另一个函数是一种很有用的抽象特定函数行为的方法。本节将给出两个使用这种编程技术的示例。

map

函数map(Func,List)返回一个列表L,其中的元素由函数Func依次作用于列表List的各个元素得到。

map(Func, [H|T]) ->
    [apply(F, [H])|map(Func, T)];
map(Func, []) ->
    [].

> lists:map({math,factorial}, [1,2,3,4,5,6,7,8]).
[1,2,6,24,120,720,5040,40320]

filter

函数filter(Pred,List)对列表List中的元素进行过滤,仅保留令Pred的值为true的元素。这里的Pred是一个返回true或false的函数。

filter(Pred, [H|T]) ->
    case apply(Pred,[H]) of
        true ->
        [H|filter(Pred, T)];
    false ->
        filter(Pred, T)
    end;
filter(Pred, []) ->
    [].

假设函数math:even/1在参数为偶数时返回true,否则返回fale,则:

> lists:filter({math,even}, [1,2,3,4,5,6,7,8,9,10]).
[2,4,6,8,10]

脚注

[1] 标记Lhs⇒Rhs代表对Lhs求值的结果为Rhs。