在对此question的答案中,响应者使用功能reduced

(defn state [t]
  (reduce (fn [[s1 t1] [s2 t2]]
            (if (>= t1 t) (**reduced** s1) [s2 (+ t1 t2)]))
          (thomsons-lamp)))


我查看了文档和源,无法完全理解它。

(defn reduced
  "Wraps x in a way such that a reduce will terminate with the value x"
  {:added "1.5"}
  [x]
  (clojure.lang.Reduced. x))


在上面的示例中,我认为(reduced s1)应该结束缩减并返回s1。

如果使用reduce + reduce等于假设的reduce-while或reduce-until函数(如果存在)?

最佳答案

减少提供了一种突破减少提供的值的方法。

例如将数字相加

(reduce (fn [acc x] (+ acc x)) (range 10))


返回45

(reduce (fn [acc x] (if (> acc 20) (reduced "I have seen enough") (+ acc x))) (range 10))


返回“我已经看够了”

09-12 10:15