如果group-by
允许用户控制聚合集合类型并在聚合之前操作值会很好。这通常是在根据一个键将映射集合分组以及根据另一个键进行聚合(甚至可能是数值聚合)的情况下。
group-by
可以被泛化如下
(defn group-by
"Returns a map of the elements of coll keyed by the result of
f on each element. The value at each key will be a vector of the
corresponding elements, in the order they appeared in coll."
{:added "1.2"
:static true}
([kf coll]
(group-by kf [] coll))
([kf init coll]
(group-by kf identity init coll))
([kf vf init coll]
(group-by kf vf conj init coll))
([kf vf rf init coll]
(persistent!
(reduce
(fn [ret x]
(let [k (kf x)]
(assoc! ret k (rf (get ret k init) (vf x)))))
(transient {}) coll))))