如何在 clojure 中打印每行的数字列表?
如何在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以为此使用doseq,这意味着当迭代涉及副作用时使用,
您可以按照指出使用map,但这会产生一个充满nils的序列,这既不惯用,又浪费资源,而且doseq不是懒惰的,所以不需要用 doall 强制它。
You can use doseq for this, which is meant to be used when iteration involves side effects,
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.
我建议使用 dotimes 对于这种简单的循环:
请注意,dotimes 是非惰性的,因此它对于像 println 这样会导致副作用的事情很有用。
I suggest dotimes for this kind of simple loop:
Note that dotimes is non-lazy, so it is good for things like println that cause side effects.
使用loop/recur:
然而,映射 函数 println 覆盖 1..10 中的数字。但由于 map 返回一个惰性序列,因此您必须强制使用 doall 进行评估:
With loop/recur:
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:
为了全面起见,您也可以使用地图来做到这一点:
And just to be comprehensive you can do it with map also:
如果您只想在屏幕上打印输出,您也可以在输入条件之前简单地放置一个
(println i)
:并且输出将是每行一个数字。
If you only want to print the output on the screen, you might also simply put a
(println i)
before entering your conditional:And the output will be one number per line.