There actually is a queue implementation. Here is a way to use it for your
problem:
(defn make-moving-average-queue [n]
(atom {:length n
:current-total 0.0
:old-values (clojure.lang.PersistentQueue/EMPTY)}))
(defn update-moving-average-queue [old-queue next-value]
(let [current-total (+ (:current-total old-queue) next-value)
old-values (conj (:old-values old-queue) next-value)]
(if (> (count old-values) (:length old-queue))
(let [current-total (- current-total (first old-values))
old-values (pop old-values)]
(assoc old-queue :current-total current-total :old-values
old-values))
(assoc old-queue :current-total current-total :old-values
old-values))))
(defn moving-average [old-queue next-value]
(let [new-queue (swap! old-queue update-moving-average-queue next-value)]
(/ (:current-total new-queue) (count (:old-values new-queue)))))
(def queue-06 (make-moving-average-queue 6))
(def inputs-06 [20 22 21 24 24 23 25 26 20 24 26 26 25 27 28 27 29 27 25
24])
(doseq [input inputs-06]
(println (moving-average queue-06 input)))
(def queue-10 (make-moving-average-queue 10))
(def inputs-10 [20 22 24 25 23 26 28 26 29 27 28 30 27 29 28])
(doseq [input inputs-10]
(println (moving-average queue-10 input)))
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.