Calculating the Moving Average of a List

后端 未结 18 1126
悲哀的现实
悲哀的现实 2020-12-07 09:01

This weekend I decided to try my hand at some Scala and Clojure. I\'m proficient with object oriented programming, and so Scala was easy to pick up as a language, but wante

18条回答
  •  不思量自难忘°
    2020-12-07 09:41

    This example makes use of state, since to me it's a pragmatic solution in this case, and a closure to create the windowing averaging function:

    (defn make-averager [#^Integer period]
      (let [buff (atom (vec (repeat period nil)))
            pos (atom 0)]
        (fn [nextval]
          (reset! buff (assoc @buff @pos nextval))
          (reset! pos (mod (+ 1 @pos) period))
          (if (some nil? @buff)
            0
            (/ (reduce + @buff)
               (count @buff))))))
    
    (map (make-averager 4)
         [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0])
    ;; yields =>
    (0 0 0 4.75 5.0 6.0 7.25 8.0 8.25 6.5)
    

    It is still functional in the sense of making use of first class functions, though it is not side-effect free. The two languages you mentioned both run on top of the JVM and thus both allow for state-management when necessary.

提交回复
热议问题