在对此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-while或reduce-until函数是否存在?
答案 0 :(得分:5)
Reduced提供了一种通过提供的值来突破减少的方法。
例如,按顺序添加数字
(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))
返回"我已经看到了足够的"