Skip to content

Instantly share code, notes, and snippets.

@KingCode
Last active February 13, 2021 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KingCode/30894e53da19d712021906629cf1583c to your computer and use it in GitHub Desktop.
Save KingCode/30894e53da19d712021906629cf1583c to your computer and use it in GitHub Desktop.
frequencies-by function
(defn frequencies-by
"Returns a map from distinct results of (f item) in coll
to a vector duple of all (k item) (if k is provided, or items otherwise)
with the same (f item) value, and the number of times (f item) appears.
"
([f coll]
(frequencies-by f nil coll))
([f k coll]
(persistent! ;; copied from clojure.core
(reduce (fn [counts x]
(assoc! counts (f x)
(let [[xs kount] (get counts (f x) [[] 0])]
[(conj xs (if k (k x) x))
(inc kount)])))
(transient {}) coll))))
@KingCode
Copy link
Author

Examples:

(frequencies-by :age :id  [{:age 10 :id 1} {:age 12 :id 2} {:age 10 :id 3}])
 ;;=> {10 [[1 3] 2] 12 [[2] 1]}

(frequencies-by even?  [1 2 3 4 5])
;;=> {true [[2 4] 2]
        false [[1 3 5] 3]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment