gpt4 book ai didi

clojure - 'reduced' 函数有什么作用以及如何使用它

转载 作者:行者123 更新时间:2023-12-04 19:06:18 25 4
gpt4 key购买 nike

在回答这个 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 函数(如果存在)?

最佳答案

Reduced 提供了一种使用提供的值打破 reduce 的方法。

例如在序列中添加数字

(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))

返回“我已经看够了”

关于clojure - 'reduced' 函数有什么作用以及如何使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23433691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com