Do-while loop in Clojure?

淺唱寂寞╮ 提交于 2019-12-29 08:38:05

问题


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)))

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?


回答1:


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))))


来源:https://stackoverflow.com/questions/8675911/do-while-loop-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!