我想跳出下面的循环,并在第 10 行计算结果为 true 时返回最佳最小移动。我查看了 print 语句的输出,当第 10 行的计算结果为 true 时,它找到了我正在查找的数据,但仍然重复出现。在 Clojure 中,有没有办法在语句计算结果为 true 时停止循环?或者我应该使用循环之外的其他东西?
(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)))))))
About loop
- 它不是
loop
循环:它是recur
.
-
loop
is a let
从而形成一个recur
point.
- 你不会也不能跳出循环:
recur
将你们合而为一。
loop
相当于设置并调用匿名函数。例如
(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
可以编写为执行上述转换的宏。
至于你的代码:
这里有六个未定义的函数。为了清除编译,我们
(declare best-min-score
best-max-move
best-min-move
best-max-move
make-move-on
remaining-scores)
还有两种冗余形式。这些不会造成任何主动损害,但会使代码变得模糊。
- The
loop
不需要:函数本身是合适的
目标为recur
.
- The
do
什么都不做:它包含一个单一的表单。
你的函数简化为
(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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)