Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure equivalent of this Haskell Moving Average Function?

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?


1 Answers

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.

like image 164
Rörd Avatar answered Sep 23 '26 21:09

Rörd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!