我想要Clojure 中Python 的itertools.accumulate()的等价物。
如果您不熟悉,它基本上是reduce()
,但它存储了每次调用 reducing 函数的输出。
我似乎无法在内置的 clojure 函数中找到 1:1 的等价物。我最接近的工作近似值是
(defn accumulate
"Like `reduce` but stores result of every step."
([f coll]
(accumulate f (first coll) (rest coll)))
([f val coll]
(loop [result [val]
current-val val
next-val (first coll)
coll (rest coll)]
(if (empty? coll)
(conj result (f current-val next-val))
(let [new-val (f current-val next-val)]
(recur (conj result new-val)
new-val
(first coll)
(rest coll)))))))
是否有执行此操作的现有功能?
如果没有,是否有更好的方法来做到这一点?
RISEBY
相关分类