退出Recur循环在Clojure [英] Exit Recur Loop in Clojure
问题描述
我想跳出下面的循环,并返回best-min-move,当第10行计算为true。我已经看过输出与打印语句,当第10行评估为真,它找到我正在寻找,但继续重复的数据。在Clojure中有一种方法可以在语句计算结果为true时停止循环?或者,我应该使用除了循环之外的其他东西吗?
I'd like break out of the below loop and return the best-min-move when line 10 evaluates to true. I've looked at the output with print statements and when line 10 does evaluate to true, it finds the data that I'm looking for but continues to recur. In Clojure is there a way to stop the loop when a statement evaluates to true? Or should I be using something other than a loop recur?
(defn minimax [board max-mark min-mark depth best-score]
(loop [board board
max-mark max-mark
min-mark min-mark
depth depth
best-score best-score]
(if (= best-score (best-min-score board max-mark min-mark depth))
(best-max-move board max-mark min-mark depth)
(do
(if (= best-score (best-min-score board min-mark max-mark depth))
(best-min-move board min-mark max-mark depth)
(recur
(b/make-move-on board (remaining-scores board max-mark min-mark depth) max-mark)
min-mark
max-mark
(inc depth)
(dec best-score)))))))
推荐答案
关于 loop
- 不是
循环
循环:recur
。 - code> loop 是一个
let
,形成一个li>
- 您不能,也不能跳出循环:
recur
/ li>
- 您不能,也不能跳出循环:
- It's not
loop
that loops: it'srecur
. loop
is alet
that forms arecur
point.- You don't and can't break out of a loop:
recur
breaks you into one.
loop
等效于设置和调用匿名函数。例如
loop
is equivalent to setting up and calling an anonymous function. For example
(loop [n 5, s "Hello, world!"]
(if (zero? n)
(first s)
(recur (dec n) (rest s))))
...等效于
((fn [n s]
(if (zero? n)
(first s)
(recur (dec n) (rest s))))
5 "Hello, world!")
由于某些性能损失, loop
可能已写为执行上述转型。
With some loss of performance, loop
could have been written as a macro that carries out the above transformation.
至于您的代码:
有六个未定义功能。要清除编辑,我们
There are six undefined functions here. To clear compilation, we
(declare best-min-score
best-max-move
best-min-move
best-max-move
make-move-on
remaining-scores)
还有两个冗余形式。这些没有积极的伤害,但掩盖了代码。
There are also two redundant forms. These do no active harm but do obscure the code.
- 不需要
循环
:函数本身是一个合适的$ b $ c 单一形式。
- The
loop
is not needed: the function itself is a suitable target forrecur
. - The
do
does nothing: it encloses a single form.
您的功能减少到
(defn minimax [board max-mark min-mark depth best-score]
(if (= best-score (best-min-score board max-mark min-mark depth))
(best-max-move board max-mark min-mark depth)
(if (= best-score (best-min-score board min-mark max-mark depth))
(best-min-move board min-mark max-mark depth)
(recur
(make-move-on board (remaining-scores board max-mark min-mark depth) max-mark)
min-mark
max-mark
(inc depth)
(dec best-score)))))
虽然任何未定义的函数可能会重现,但最好的办法是 best-min-move
。
这篇关于退出Recur循环在Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!