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