Clojure 中的 Do-while 循环? [英] Do-while loop in Clojure?
问题描述
所以我想先执行一堆代码,然后然后询问用户他是否想再次这样做.我认为最方便的方法是在 C++ 中使用 do-while 循环,而且由于我在 Clojure 中似乎找不到任何 do-while 函数,所以我写了以下内容:
So I want to first execute a bunch of code, and then ask the user if he wants to do that again. I thought the most convenient way to do this would be a do-while loop like in C++, and since I couldn't seem to find any do-while functions in Clojure, I wrote the following:
(defmacro do-while
"Executes body before testing for truth expression"
[test & body]
`(do (do ~@body) (while ~test ~@body)))
是否有更好的方式(如更惯用的 Clojure-ish)来编写这个宏,或者可能有更好的方式来做我想做的事情而不经过 do-while 路线?
Would there be a better (as in more idiomatic Clojure-ish) way of writing this macro, or perhaps a better way of doing what I want without going through the do-while route?
推荐答案
这里是 Clojure 的 的一个稍微改变的版本while
宏,在评估主体后进行测试:
Here is a slightly changed version of Clojure's while
macro, where the test is done after evaluating the body:
(defmacro do-while
[test & body]
`(loop []
~@body
(when ~test
(recur))))
这篇关于Clojure 中的 Do-while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!