5

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.

2240
  • 1,547
  • 2
  • 12
  • 30
kharandziuk
  • 12,020
  • 17
  • 63
  • 121

1 Answers1

9

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.

Community
  • 1
  • 1
bereal
  • 32,519
  • 6
  • 58
  • 104