我试图在遇到异常前多次执行一个函数,但在Clojure中从catch块中进行recur不被认为是有效的。如何实现这一点?
(loop [tries 10]
(try
(might-throw-exception)
(catch Exception e
(when (pos? tries) (recur (dec tries))))))
java.lang.UnsupportedOperationException: Cannot recur from catch/finally
我能找到的最好解决方案是以下笨拙的方法(将其包装在函数中并调用它)
(defn do-it []
(try
(might-throw-exception)
(catch Exception e nil)))
(loop [times 10]
(when (and (nil? (do-it)) (pos? times))
(recur (dec times))))
#
,以供调用者创建thunk。在Clojure中使用宏仅仅为了省略#
是惯用的吗? - Dax Fohl