Skip to content

Instantly share code, notes, and snippets.

@tgk
Created June 18, 2013 08:03
Show Gist options
  • Save tgk/5803480 to your computer and use it in GitHub Desktop.
Save tgk/5803480 to your computer and use it in GitHub Desktop.
Simple aggregator macro
(defmacro aggregate
"Simple aggregation. Iterates over seq, binding values to
seq-bind. agg-bind is initially initial-val, but is bound to the value
of body after each iteration, and returned as the final value."
[agg-bind initial-val
[seq-bind seq]
& body]
`(reduce
(fn [~agg-bind ~seq-bind]
(do ~@body))
~initial-val
~seq))
(aggregate a {:sum 0}
[i (range 10)]
{:sum (+ i (:sum a))})
;; => {:sum 45}
(aggregate [count sum] [0 0]
[i (range 10)]
[(inc count) (+ sum i)])
;; => [10 45]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment