在 Erlang 中作为参数的函数

Function as an argument in Erlang

我正在尝试做这样的事情:

-module(count).
-export([main/0]).
        
sum(X, Sum) -> X + Sum.

main() ->
    lists:foldl(sum, 0, [1,2,3,4,5]).

但看到警告并且代码失败:

function sum/2 is unused

如何修复代码?

注意: 这只是一个说明问题的示例,因此没有理由提出使用 fun-表达式的解决方案。

Erlang 对此有更明确的语法:

-module(count).
-export([main/0]).

sum(X, Sum) -> X + Sum.
main() ->
    lists:foldl(fun sum/2, 0, [1,2,3,4,5]).

另见“Learn you some Erlang”:

If function names are written without a parameter list then those names are interpreted as atoms, and atoms can not be functions, so the call fails.

...

This is why a new notation has to be added to the language in order to let you pass functions from outside a module. This is what fun Module:Function/Arity is: it tells the VM to use that specific function, and then bind it to a variable.