函数
1. 写法
FunctionName() -> xxx.
2. 函数数据类型为 fun
匿名函数
1. 概念
不定义函数名的函数,被称为匿名函数
2. 写法
fun(参数) -> xxx end.
函数可以作为参数
%% 定义一个列表
> List = [ 1, 2, 3 ].
%% lists:map(处理函数, L) 是个内置函数
%% 作用:把列表L里的各个元素 传递给 处理函数,返回的结果组成新的列表
> lists:map(fun(X) -> X * 2 end, L).
[ 2, 4, 6 ]
函数可以做为返回值
%% 定义初始化水果列表的函数
%% list:member(CheckTarget, FruitList) 判断 CheckTarget 是否在 FruitList 中
> InitFruitList = fun(FruitList) -> (fun(CheckTarget) -> lists:member(CheckTarget, FruitList) end) end.
%% 初始化本次的列表, 返回了匿名函数函数
%% fun(CheckTarget) -> lists:member(CheckTarget, [ apple, orange ]) end.
> IsFruit = InitFruitList([ apple, orange ]).
%% 判断是否是水果
> IsFruit(apple).
True
> IsFruit(dog).
False