Calculating the Moving Average of a List

后端 未结 18 1120
悲哀的现实
悲哀的现实 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:31

    Here's a clojure version:

    Because of the lazy-seq, it's perfectly general and won't blow stack

    (defn partialsums [start lst]
      (lazy-seq
        (if-let [lst (seq lst)] 
              (cons start (partialsums (+ start (first lst)) (rest lst)))
              (list start))))
    
    (defn sliding-window-moving-average [window lst]
      (map #(/ % window)
           (let [start   (apply + (take window lst))
                 diffseq (map   - (drop window lst) lst)]
             (partialsums start diffseq))))
    

    ;; To help see what it's doing:

    (sliding-window-moving-average 5 '(1 2 3 4 5 6 7 8 9 10 11))
    
    start = (+ 1 2 3 4 5) = 15
    
    diffseq = - (6 7 8 9 10 11)
                (1 2 3 4  5  6 7 8 9 10 11)
    
            =   (5 5 5 5  5  5)
    
    (partialsums 15 '(5 5 5 5 5 5) ) = (15 20 25 30 35 40 45)
    
    (map #(/ % 5) (20 25 30 35 40 45)) = (3 4 5 6 7 8 9)
    

    ;; Example

    (take 20 (sliding-window-moving-average 5 (iterate inc 0)))
    

提交回复
热议问题