我越来越了解Erlang语言,并最近遇到了一些问题。我阅读了关于foldl(Fun, Acc0, List) -> Acc1
函数的内容。我使用了learnyousomeerlang.com教程,其中有一个例子(该例子是关于Erlang中的逆波兰计算器):
%function that deletes all whitspaces and also execute
rpn(L) when is_list(L) ->
[Res] = lists:foldl(fun rpn/2, [], string:tokens(L," ")),
Res.
%function that converts string to integer or floating poitn value
read(N) ->
case string:to_float(N) of
%returning {error, no_float} where there is no float avaiable
{error,no_float} -> list_to_integer(N);
{F,_} -> F
end.
%rpn managing all actions
rpn("+",[N1,N2|S]) -> [N2+N1|S];
rpn("-", [N1,N2|S]) -> [N2-N1|S];
rpn("*", [N1,N2|S]) -> [N2*N1|S];
rpn("/", [N1,N2|S]) -> [N2/N1|S];
rpn("^", [N1,N2|S]) -> [math:pow(N2,N1)|S];
rpn("ln", [N|S]) -> [math:log(N)|S];
rpn("log10", [N|S]) -> [math:log10(N)|S];
rpn(X, Stack) -> [read(X) | Stack].
据我所知,
lists:foldl
在列表中的每个元素上执行 rpn/2
。但这就是我对该函数的理解。我阅读了文档,但并没有帮助我很多。能否有人解释一下lists:foldl
是如何工作的?