gpt4 book ai didi

haskell - 这个 Haskell 移动平均函数的 Clojure 等价物?

转载 作者:行者123 更新时间:2023-12-04 02:44:05 25 4
gpt4 key购买 nike

试图了解 Clojure 和 Haskell 之间的区别。我有以下代码计算时间序列数字列表的移动平均值:

movavg n []     = []
movavg n (x:xs) = map (/ n') sums
where
sums = scanl (+) (n' * x) $ zipWith (-) xs (replicate n x ++ xs)
n' = fromIntegral n

这在 Clojure 中的惯用版本是什么?

最佳答案

我不明白为什么这个非常字面的翻译不应该是地道的,即:

(defn movavg [n coll]
(when-let [[x & xs] (seq coll)]
(map #(/ % n)
(reductions + (* n x)
(map - xs (concat (repeat n x) xs))))))

特别是具有大量序列函数的代码总是有可能非常接近 Haskell,因为它们是惰性的。

编辑:根据 Justin Kramer 的建议缩短了代码。

关于haskell - 这个 Haskell 移动平均函数的 Clojure 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19240191/

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