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

1

17

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?

Leralerch answered 27/12, 2012 at 23:14 Comment(1)
General advice: Don't use side-effect functions for map operationYanez
B
31

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

Bosanquet answered 27/12, 2012 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.