3

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
    is this one equivalent? http://stackoverflow.com/a/1320425/24946 – Jonas Oct 08 '13 at 06:30
  • 1
    No, not in terms of efficiency. The difference is in the way that redundant computations are eliminated. –  Oct 08 '13 at 06:57
  • I can't get the haskell code to work, can you provide a simple example where you are invoking movavg? – Jonas Oct 08 '13 at 07:34

1 Answers1

4

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.

Rörd
  • 6,556
  • 21
  • 27