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.
Calling the function involves specifying the function name, followed by the function call operator and any data values the function expects to receive. These values are the arguments for the parameters defined for the function. This process is called passing arguments to the function.
A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. A function named f in the module m and with arity N is often denoted as m:f/N.
Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With