gpt4 book ai didi

clojure - clojure 的目的是减少函数

转载 作者:行者123 更新时间:2023-12-04 00:44:19 24 4
gpt4 key购买 nike

clojure的目的是什么reduced函数(在 clojure 1.5 中添加, https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reduced )

我找不到任何例子。医生说:

Wraps x in a way such that a reduce will terminate with the value x.



还有一个 reduced?熟悉它的人

Returns true if x is the result of a call to reduced



当我尝试时,例如使用 (reduce + (reduced 100)) , 我得到一个错误而不是 100。另外,当我提前知道结果时,为什么我要减少一些东西?由于它被添加,可能是有原因的,但谷歌搜索 clojure reduced仅包含 reduce结果。

最佳答案

reduced允许您短路减少:

(reduce (fn [acc x]
(if (> acc 10)
(reduced acc)
(+ acc x)))
0
(range 100))
;= 15

(注意。从 Clojure 1.6 开始,作为初始值传入的 (reduced 0) 的边缘情况不起作用。)

这很有用,因为 reduce -based 循环既非常优雅又非常高效(以至于 reduce -based 循环的性能通常比基于 loop/ recur 的“自然”替换更高效),所以制作这种模式很好尽可能广泛地适用。短路能力 reduce大大增加了可能的应用范围。

至于 reduced? ,我发现它主要在实现 reduce 时很有用新数据结构的逻辑;在常规代码中,我让 reduce发挥自己的作用 reduced?在适当的地方检查。

关于clojure - clojure 的目的是减少函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25106988/

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