Erlang中作为参数的函数

qacovj5a  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(180)

I'm trying to do something like this:

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

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

but see a warning and code fails:

function sum/2 is unused

How to fix the code?

NB: this is just a sample which illustrates problem, so there is no reason to propose solution which uses fun -expression.

ckocjqey

ckocjqey1#

Erlang has slightly more explicit syntax for that:

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

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

See also " 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.

相关问题