Using lists:map/2 with a named function
Tuesday, 11th May, 2010
When using a named function (i.e., rather than an anonymous function) with lists:map/2, it is necessary to use the form fun module:function/arity. For example, the module [1] will raise the error [2]:
[1]
-module(maptest).
-export([test/0]).
-export([double/1]).
double(N) ->
2 * N.
test() ->
List = [1,2,3,4,5],
lists:map(double, List).
[2]
1> c(maptest).
{ok,maptest}
2> maptest:test().
** exception error: bad function double
in function lists:map/2
Module [3] works:
[3]
-module(maptest).
-export([test/0]).
%% -export([double/1]). %% not necessary
double(N) ->
2 * N.
test() ->
List = [1,2,3,4,5],
lists:map(fun double/1, List).
[4]
1> c(maptest).
{ok,maptest}
2> maptest:test().
[2,4,6,8,10]
So the first argument of map — whether the function is named or anonymous — always starts with the keyword fun:
[5]
lists:map(fun(X) -> 2 * X end, List).
As an aside, it is not necessary to export the function in order to make it accessible to map (cf. [3]).
This is a summary of recent discussion on the erlang-programming-book Google group.