减少我想要聚合大量的数据可能要达到这样的组用Clojure中
SELECT SUM(`profit`) as `profit`, `month` FROM `t` GROUP BY `month`
所以,我修改Clojure的组,按功能,像这样
(defn group-reduce [f red coll]
(persistent!
(reduce
(fn [ret x]
(let [k (f x)]
(assoc! ret k (red (get ret k) x))))
(transient {}) coll)))
而这里的用法:
(group-reduce :month (fn [s x]
(if s
(assoc s :profit (+ (:profit s) (:profit x)))
x))
[{:month 10 :profit 12}
{:month 10 :profit 15}
{:month 12 :profit 1}])
#_=> {10 {:profit 27, :month 10}, 12 {:profit 1, :month 12}}
它的工作,但也许有另一种方式来做到这一点,使用clojure标准库?
东西是不完全正确这里。我预计第10个月的总利润为27美元。 – 2013-03-22 14:32:18
对不起,当然是,只是一个错字。固定。 – h3x3d 2013-03-22 15:59:43
不,我使用它很多,这里例如https://github.com/cgrand/utils/blob/master/src/net/cgrand/utils.clj#L8 – cgrand 2013-03-26 10:12:38