14

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?

1
  • 3
    using (doseq [x myVec] (println x))
    – BLUEPIXY
    Commented Dec 16, 2011 at 22:38

3 Answers 3

10

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.

3
  • A little of the confusion comes from the order in which the data gets printed out. The initial parenthesis gets printed as part of the list that (map (println...)) returns, then you get the output of each println, then the nils that are part of the list of (map (println ...)). If you switch to using doseq, or if you (doall (map (println ...))), the results will be a bit less ambiguous as you will see all of the prints before you get the return values. (dorun (map (println ...))) will return just. Unless I got dorun and doall reversed. Commented Dec 16, 2011 at 16:31
  • 4
    @SavanniD'Gerinel The things you're saying are vaguely true, but wrong in most of the particulars. Things come out in the "wrong" order because the sequence is chunked, not because the repl prints side effects before values: if you had an unchunked sequence like (take 10 (iterate #(inc (doto % println)) 0)), you would see return values interleaved with print results. Similarly if you had a list bigger than a single chunk (say, of size 50), you would get a bunch of prints, then a bunch of values, then more prints...
    – amalloy
    Commented Dec 16, 2011 at 19:12
  • That's informative. The gist of what I was saying was that you couldn't really predict the order in which things were printed, but even that would have been inaccurate given the chunking you refer to here. As it stands, I only became aware of chunking a few days ago. Commented Dec 19, 2011 at 17:41
7

Those nil are the return value of println. Every time you call

(println "something")

the println function prints something on the standard output, and then returns nil. The overall effect in your code is that you see all the side effects (I/O) of all println invocations, then the REPL prints the return value coming from each and every invocation (e.g. three times nil).

1

nil is the value returned by println so you are seeing the printed lines followed by the mapped list of nil values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.