Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

functional programming - Do-while loop in Clojure?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...