clojure功能的目的 [英] purpose of clojure reduced function
问题描述
clojure reduce
函数的目的是什么(在clojure 1.5中添加, https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reduced )
What is the purpose of the clojure reduced
function (added in clojure 1.5, https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/reduced)
我找不到任何例子。文档说:
I can't find any examples for it. The doc says:
以某种方式换行x,使得reduce将以值x终止。
Wraps x in a way such that a reduce will terminate with the value x.
还有一个已减少?
>
There is also a reduced?
which is acquainted to it
如果x是调用减少的结果,则返回true
Returns true if x is the result of a call to reduced
$ b b
当我尝试它,例如与(减少+(减少100))
,我得到一个错误,而不是100.也为什么我会减少一些东西,当我知道结果提前?因为它被添加可能有一个原因,但是搜索 clojure减少
只包含 reduce
结果。
When I try it out, e.g with (reduce + (reduced 100))
, I get an error instead of 100. Also why would I reduce something when I know the result in advance? Since it was added there is likely a reason, but googling for clojure reduced
only contains reduce
results.
推荐答案
reduced
可让您缩短缩图:
(reduce (fn [acc x]
(if (> acc 10)
(reduced acc)
(+ acc x)))
0
(range 100))
;= 15
(NB。边界情况与(减少0)
传递作为初始值不工作的Clojure 1.6)
(NB. the edge case with (reduced 0)
passed in as the initial value doesn't work as of Clojure 1.6.)
这很有用,因为 reduce
基于循环非常优雅和非常基于 loop
的基于 reduce
的循环的性能不如常常高于 / recur
),因此尽可能使此模式尽可能广泛适用是好的。短路减少的能力大大增加了可能的应用程序的范围。
This is useful, because reduce
-based looping is both very elegant and very performant (so much so that reduce
-based loops are not infrequently more performant than the "natural" replacements based on loop
/recur
), so it's good to make this pattern as broadly applicable as possible. The ability to short circuit reduce
vastly increases the range of possible applications.
对于减少?
,我发现它对于新数据结构实现 reduce
逻辑时很有用;在正常代码中,我让减少
在适当时执行自己的减少
检查。
As for reduced?
, I find it useful primarily when implementing reduce
logic for new data structures; in regular code, I let reduce
perform its own reduced?
checks where appropriate.
这篇关于clojure功能的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!