python在clojure中的累积等价物

我想要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)))))))

是否有执行此操作的现有功能?


如果没有,是否有更好的方法来做到这一点?


跃然一笑
浏览 159回答 1
1回答

RISEBY

您正在寻找reductions. 但是您的自定义函数也可以大大简化:(defn accumulate [f coll]      (reduce #(conj %1 (f (last %1) %2)) [(first coll)] (rest coll)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python