Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function as an argument in Erlang

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.

like image 235
kharandziuk Avatar asked Jun 30 '15 10:06

kharandziuk


People also ask

Can a function call be an argument?

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.

How do you define a function in Erlang?

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.

How are arguments passed through function call?

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.


1 Answers

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.

like image 171
bereal Avatar answered Nov 02 '22 16:11

bereal