Created
June 18, 2013 08:03
-
-
Save tgk/5803480 to your computer and use it in GitHub Desktop.
Simple aggregator macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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