Reputation:
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?
Upvotes: 3
Views: 537
Reputation: 6681
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.
Upvotes: 4