开发者

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.


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.


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.


With loop/recur:

(loop [i 1]
  (when (<= i 10)
    (println i)
    (recur (inc i))))

However, it's more idiomatic (read: more "Clojuristic") to map the function println over the numbers in 1..10. But because map returns a lazy sequence, you must force its evaluation with doall:

(doall (map println (range 1 (inc 10))))


And just to be comprehensive you can do it with map also:

(doseq (map #(println %) (range 10))


If you only want to print the output on the screen, you might also simply put a (println i) before entering your conditional:

(loop [i 0]
  (println i)
  (if (< i 10)
    (recur (inc i))
    (println "done!")))

And the output will be one number per line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜