Attempting to understand the differences between Clojure and Haskell. I have the following code which calculates the moving average of a time-series list of numbers:
movavg n [] = []
movavg n (x:xs) = map (/ n') sums
where
sums = scanl (+) (n' * x) $ zipWith (-) xs (replicate n x ++ xs)
n' = fromIntegral n
What would be the idiomatic version of this in Clojure?
I don't see why a very literal translation of this shouldn't be idiomatic, i.e.:
(defn movavg [n coll]
(when-let [[x & xs] (seq coll)]
(map #(/ % n)
(reductions + (* n x)
(map - xs (concat (repeat n x) xs))))))
Particularly code with a lot of sequence functions has always the potential to be very close to Haskell since they're lazy.
Edit: Shortened code according to Justin Kramer's suggestion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With