Clojure中的Do-while循环? [英] Do-while loop in Clojure?

查看:219
本文介绍了Clojure中的Do-while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想先执行一堆代码,然后 询问用户是否想再做一次。我认为最方便的方法是使用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的的略微更改版本,而 macro ,其中测试在评估正文之后完成:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆