Skip to content

Instantly share code, notes, and snippets.

@sritchie
Created February 9, 2011 07:00
Show Gist options
  • Select an option

  • Save sritchie/818074 to your computer and use it in GitHub Desktop.

Select an option

Save sritchie/818074 to your computer and use it in GitHub Desktop.
moving averages.
;; We define simpler functions first, so we know here that this'll get used below...
(defn average
"Takes the average of all numbers in the supplied collection."
[coll]
(/ (apply + coll)
(count coll)))
;; here's a nice, effectively one line solution. (It's often the case that the docstring will be longer than the function itself.)
(defn moving-average
"Returns a moving average of windows into the supplied
collection. Example usage:
(moving-average 5 [4 9 23 23 1 2 8 6 4 87])
;=> (12 58/5 57/5 8 21/5 107/5)"
[window coll]
(map average (partition window 1 coll)))
;; Condensed version of the above two. Here, we define an anonymous function inline using #(). You can represent arguments as % or %1, %2, %3, etc; we only have one argument, here.
(defn moving-average [window coll]
(map #(/ (apply + %) window)
(partition window 1 coll)))
;; We also could have written:
(defn moving-average [window coll]
(map (fn [coll]
(/ (apply + coll) window))
(partition window 1 coll)))
;; the first version with the #() expands out to this. (I added the newline after [coll] for looks, but we could have left it at one line.)
;; Remember, all functions are declared with fn, under the hood! Usually, we wrap them up in a var, with
;; (def average (fn [coll] ... etc)). This is what it means to divorce the identity, the var, or average, from the actual thing, or that anonymous function.
;; Dan, you've probably read this, but (def square (fn [x] (* x x))) is equivalent to (defn square [x] (* x x)). defn is a macro that actually writes
;; the previous code. You can use the macroexpand-1 tool in Textmate (I don't know which key command!) to expand macros and see the code they write.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment