如何在Clojure for循环运行时更改:while条件?

Dan*_*son 2 for-loop clojure

我正在寻找满足某些条件的最大数字,这些数字是所有三位数字的乘积.

直截了当的方式是这样的:

(apply max (filter 
            my-test? 
            (for [x (range 100 1000)
                  y (range x 1000)]
              (* x y))))
Run Code Online (Sandbox Code Playgroud)

但这涉及计算所有900*900产品中的一半.如果我发现,例如,(* 380 455)匹配我的my-test?谓词,我不需要搜索任何因子小于380的产品.当然,如果我这样做,我也想搜索从最大到最小的列表.

在psuedo-Clojure中,我想说这样的话:

(for [x (range 999 99 -1) :while (>= x P)
      y (range x 99 -1) :while (>= y P)]
  (* x y))
Run Code Online (Sandbox Code Playgroud)

这里P是我神奇地设置为(min x y)每个我找到了比赛时间.

有没有办法在Clojure中做到这一点?

(我意识到我可以以对角线的方式搜索数字,考虑到我已经设置的这个特定问题.但是,我现在正试图解决一般情况下找出如何告诉for-loop它的一些分支需要修剪.)

Dan*_*son 5

@omeil提出了loop/ recur进程,这个工程太大更好. for循环只是不是为此而构建的.

(loop [x 999 y 999 min 99 candidates []]
    (cond (<= x min)          candidates ; exit condition
          (<= y min)          (recur (dec x) 999 min candidates) ; step x
          (my-test? (* x y)) (recur x (dec y) (max min y) (conj candidates (* x y)))
          :else               (recur x (dec y) min candidates) ; step y
     ))
Run Code Online (Sandbox Code Playgroud)