Skip to content

Instantly share code, notes, and snippets.

@lynaghk
Created November 2, 2011 16:20
Show Gist options
  • Save lynaghk/1334086 to your computer and use it in GitHub Desktop.
Save lynaghk/1334086 to your computer and use it in GitHub Desktop.
Counting occurrences of items in a collection
;;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