Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weirdness in clojure map function

Tags:

list

clojure

the first strange thing about map in clojure is in following snippet:

(apply map list '((1 a) (2 b) (3 c)))

The result is surprising for me:

((1 2 3) (a b c))

Anyone could explain how it works?

like image 484
Dfr Avatar asked Mar 20 '11 14:03

Dfr


1 Answers

(apply f x '(y z)) is equivalent to (f x y z), so your code is equivalent to (map list '(1 a) '(2 b) '(3 c)).

When called with multiple lists, map iterates the lists in parallel and calls the given function with one element from each list for each element (i.e. the first element of the result list is the result of calling the function with the first element of each list as its arguments, the second is the result for the second elements etc.).

So (map list '(1 a) '(2 b) '(3 c)) first calls list with the first elements of the lists (i.e. the numbers) as arguments and then with the second elements (the letters). So you get ((list 1 2 3) (list 'a 'b 'c)).

like image 133
sepp2k Avatar answered Oct 19 '22 15:10

sepp2k