減少我想要聚合大量的數據可能要達到這樣的組用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