如果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))))