Created
November 2, 2011 16:20
-
-
Save lynaghk/1334086 to your computer and use it in GitHub Desktop.
Counting occurrences of items in a collection
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
;;Three ways to count the number of occurrences in a collection | |
;; ("orange" "bottle" "coke" "bottle") => [("bottle" "coke" "orange") (2 1 1)] | |
(let [c '("orange" "bottle" "coke" "bottle")] | |
(let [counts (reduce #(conj %1 (hash-map %2 (inc (get %1 %2 0)))) | |
{} c)] | |
[(keys counts) | |
(vals counts)]) | |
(let [l (for [[k v] (group-by identity c)] | |
[k (count v)])] | |
[(map first l) | |
(map second l)]) | |
(let [counts (apply merge-with + | |
(map #(apply hash-map %) | |
(partition 2 (interleave c (repeat 1)))))] | |
[(keys counts) | |
(vals counts)])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment