Ryan1
Ryan1

Reputation: 25

What is the syntax error in this map expression?

Regarding the following map expression:

map(_, []) -> [];
map(F, [X|XS]) -> [F(X)| map(F, XS)].

map(fun(X) -> X*X end, [2,3,4,5,6]).

There is a error before the '.' on this last line. I for the life of me can't figure out what it is.

Upvotes: 1

Views: 46

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

map(_, []) -> [];
map(F, [X|XS]) -> [F(X)| map(F, XS)].

Is function definition and belongs to a module.

map(fun(X) -> X*X end, [2,3,4,5,6]).

Is an expression and belongs inside some function definition or shell. Like this:

$ cat > my_lists.erl
-module(my_lists).

-export([map/2, squares/0]).

map(_, []) -> [];
map(F, [X|XS]) -> [F(X)| map(F, XS)].

squares() -> map(fun(X) -> X*X end, [2,3,4,5,6]).
$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.3  (abort with ^G)
1> c(my_lists).
{ok,my_lists}
2> my_lists:map(fun(X) -> X*X end, [2,3,4,5,6]).
[4,9,16,25,36]
3> my_lists:squares().
[4,9,16,25,36]
4>
User switch command
 --> q
$

Upvotes: 2

Related Questions