Reputation: 79
I am playing around with example code from Programming with Erlang. I am struck with funs. help me understand whats going wrong with below code.
-export([totalcost/1]).
Costeach = fun(X) -> {W,Q} = X, shop:cost(W)*Q end.
sum(H|T) -> H + sum[T];
sum([]) -> 0.
totalcost(L) -> sum(lists:map(Costeach,L)).
All i wanted to achieve was being able to pass Variable (with fun assigned to it) as parameter to map. get total cost from this module
i keep getting syntax error/ Costeach not initialized error.
Upvotes: 4
Views: 271
Reputation: 222408
You cannot define a function like that at the top level. You have two options: use the syntax you're using but declare it inside a named function, or declare it like a named function and use fun name/arity
syntax to convert it to an anonymous function to pass into lists:map
.
First approach:
sum(H|T) -> H + sum[T];
sum([]) -> 0.
totalcost(L) ->
Costeach = fun(X) -> {W,Q} = X, shop:cost(W)*Q end.
sum(lists:map(Costeach,L)).
Second approach:
costeach(X) -> {W,Q} = X, shop:cost(W)*Q.
sum(H|T) -> H + sum[T];
sum([]) -> 0.
totalcost(L) -> sum(lists:map(fun costeach/1,L)).
Tip: you can do the destructure in the function arguments in both cases to save a line of code:
Costeach = fun({W,Q}) -> shop:cost(W)*Q end.
or
costeach({W, Q}) -> shop:cost(W)*Q.
Upvotes: 6