如何在 clojure 中打印每行的数字列表?

发布于 2024-11-18 04:58:58 字数 211 浏览 6 评论 0原文

如何在 10 行上打印包含 n 个(例如 10 个)数字的列表?我刚刚了解了循环和递归,但似乎无法将副作用 (println i)(recur (+ i 1)) 以循环形式结合起来。 非常清楚的是:我想要这样的输出:

1
2
3
4
5
6
7
8
9
10

当 n 为 10 时。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

屋檐 2024-11-25 04:58:58

您可以为此使用doseq,这意味着当迭代涉及副作用时使用,

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

您可以按照指出使用map,但这会产生一个充满nils的序列,这既不惯用,又浪费资源,而且doseq不是懒惰的,所以不需要用 doall 强制它。

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.

嘿看小鸭子会跑 2024-11-25 04:58:58

我建议使用 dotimes 对于这种简单的循环:

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

请注意,dotimes 是非惰性的,因此它对于像 println 这样会导致副作用的事情很有用。

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.

你是暖光i 2024-11-25 04:58:58

使用loop/recur:

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

然而,映射 函数 println 覆盖 1..10 中的数字。但由于 map 返回一个惰性序列,因此您必须强制使用 doall 进行评估

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

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))))
是你 2024-11-25 04:58:58

为了全面起见,您也可以使用地图来做到这一点:

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

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

(doseq (map #(println %) (range 10))
阳光下慵懒的猫 2024-11-25 04:58:58

如果您只想在屏幕上打印输出,您也可以在输入条件之前简单地放置一个 (println i)

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

并且输出将是每行一个数字。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文