为了账号安全,请及时绑定邮箱和手机立即绑定

python在clojure中的累积等价物

python在clojure中的累积等价物

跃然一笑 2023-06-20 10:39:24
我想要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)))))))是否有执行此操作的现有功能?如果没有,是否有更好的方法来做到这一点?
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

您正在寻找reductions. 但是您的自定义函数也可以大大简化:

(defn accumulate [f coll] 
    (reduce #(conj %1 (f (last %1) %2)) [(first coll)] (rest coll)))



查看完整回答
反对 回复 2023-06-20
  • 1 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号