Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does clojure's map behave that way with println?

Hello I'm learning clojure and I want to understand what's going on, when I type

(map println '(1 2 3 4))

I expected something like

1
2
3
4

but I got

(1
2
nil 3
nil 4
nil nil)

This is just an example I made up. I just want to understand what's going on. Maybe something to do with lazyness?

like image 650
MLmuchAmaze Avatar asked Dec 27 '12 23:12

MLmuchAmaze


1 Answers

the result of running (map println ...) is a collection of the result of running println which is nil. So the result is a collection of (nil nil nil nil) which the REPL prints. while it is printing this the println calls also print there output to the REPL so you see the two mixed together.

if you define this without printing it:

user=> (def result (map println [1 2 3 4]))
#'user/result

nothing happens initially because result is lazy. If we realize it without printing it using dorun

user=> (dorun result)
1
2
3
4
nil

we see the side effects of each println and then the return value of dorun which is nil. We can then look at the contents of result by evaluating it

user=> result
(nil nil nil nil)

and see that it returns a bunch of nils

like image 159
Arthur Ulfeldt Avatar answered Oct 29 '22 11:10

Arthur Ulfeldt