apply and map in clojure

It is a very confusing comparison between map and apply.

1
2
; data preparation
(def data [[1,2,3],[1,3,4],[1,5,6]])

The famous function map means to call function provided to each element in collection once at a time.

1
2
3
4
5
6
(map println data)

;[1 2 3]
;[1 3 4]
;[1 5 6]
;(nil nil nil)

There are 3 elements in data, map calls println for each element.

Whereas appy just call function once, but extract all elements from collection before calling.

1
2
3
4
(apply println data)

;[1 2 3] [1 3 4] [1 5 6]
;nil

Here only has 1 line of printing.

Some more experiments:

1
2
3
4
5
6
(apply map println data)

;1 1 1
;2 3 5
;3 4 6
;(nil nil nil)

Obviously, apply extracts elements from collection.

1
2
3
4
5
6
7
8
(eval `(map println ~@data))
;this is equivalent to
(map println [1,2,3] [1,3,4] [1,5,6])

;1 1 1
;2 3 5
;3 4 6
;(nil nil nil)

apply and map in clojure
https://rug.al/2015/2015-04-26-apply-and-map-in-clojure/
Author
Rugal Bernstein
Posted on
April 23, 2015
Licensed under