Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a list of numbers on each line in clojure?

how can I print a list of n, say 10, numbers on 10 lines? I just learned about loop and recur, but cannot seem to combine a side-effect (println i) with (recur (+ i 1)) in a loop form. Just to be very clear: I'd like output like this:

1
2
3
4
5
6
7
8
9
10

when n is 10.

like image 457
Roger Avatar asked Jun 29 '11 12:06

Roger


2 Answers

I suggest dotimes for this kind of simple loop:

(dotimes [i 10]
  (println (inc i)))

Note that dotimes is non-lazy, so it is good for things like println that cause side effects.

like image 196
mikera Avatar answered Oct 25 '22 21:10

mikera


You can use doseq for this, which is meant to be used when iteration involves side effects,

(doseq [i (range 10)]
   (println i))

You could use map as pointed but that will produce a sequence full of nils which is both not idiomatic and wastes resources also doseq is not lazy so no need to force it with doall.

like image 30
Hamza Yerlikaya Avatar answered Oct 25 '22 22:10

Hamza Yerlikaya