Anonymous user
Apply a callback to an array: Difference between revisions
Added Erlang Task
m (→[[Apply a callback to an array#ALGOL 68]]: fix pre tag) |
(Added Erlang Task) |
||
Line 417:
io.format("squares3 : ~p~n", [squares3(Numbers)])
}
</lang>
=={{header|Erlang}}==
A list would be more commonly used in Erlang rather than an array.
<lang Erlang>
1> L = [1,2,3].
[1,2,3]
</lang>
You can use lists:foreach/2 if you just want to apply the callback to each element of the list.
<lang>
2> lists:foreach(fun(X) -> io:format("~w ",[X]) end, L).
1 2 3 ok
</lang>
Or you can use lists:map/2 if you want to create a new list with the result of the callback on each element.
<lang Erlang>
3> lists:map(fun(X) -> X + 1 end, L).
[2,3,4]
</lang>
Or you can use lists:foldl/3 if you want to accumulate the result of the callback on each element into one value.
<lang Erlang>
4> lists:foldl(fun(X, Sum) -> X + Sum end, 0, L).
6
</lang>
|