Last active
February 13, 2021 15:35
-
-
Save KingCode/30894e53da19d712021906629cf1583c to your computer and use it in GitHub Desktop.
frequencies-by function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples: