Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over vectors

I am new to Clojure and have found that when I loop over this vector in clojure using a list comprehension I get some nils at the end.

(def myVec [1,2,3])

user=> (for [x myVec] (println x))
(1
2
3
nil nil nil)

I get the same thing using map

user=> (map println myVec)
(1
2
3
nil nil nil)

What causes the nill to be printed in these cases?

like image 772
Jim Jeffries Avatar asked Dec 16 '11 15:12

Jim Jeffries


1 Answers

for and map create a new lazy sequence with every element in the original vector replaced by the result of (println element), and println returns nil.

You should not be using for and map to perform side-effects (like printing) on the elements. Use doseq for that.

like image 165
Joost Diepenmaat Avatar answered Nov 09 '22 12:11

Joost Diepenmaat