lists:map(lists:sum,[[1,2,3,4],[1,2,3]) is not allowed. Instead of list:sum there must be a fun?

Viewed 71

Why is the following not allowed:

156> lists:map(lists:sum,[[1,2,3,4],[1,2,3]).                       
* 1: illegal expression

, and when I make a fun around lists:sum, it is allowed:

162> lists:map(fun (L)->lists:sum(L)end,[[1,2,3,4],[1,2,3]]).
[10,6]

?

2 Answers

@spkhaira answer is correct, reasoning behind this syntax decision is that in Erlang functions and variables occupies different namespaces, it is similar to Lisps 2. This is mostly because of 2 reasons:

  • Erlang is dynamically typed language
  • Functions in Erlang are defined by 2 values: it's name and arity (amount of arguments)

With these 2 properties we cannot deduce what "version" of the function you want to call, that is why you need to use /N. What about fun prefix? It is just needed for parser to differentiate between erlang:'/' (aka division) and /N that is used for defining arity.

Try this -

lists:map(fun lists:sum/1,[[1,2,3,4],[1,2,3]]).
Related