Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Last active December 17, 2015 15:29
Show Gist options
  • Save skatenerd/5632287 to your computer and use it in GitHub Desktop.
Save skatenerd/5632287 to your computer and use it in GitHub Desktop.
(defn increment-in-map [map key]
(update-in map [key] #(inc (or % 0))))
(defn count-occurrences [to-count]
(loop [counted-so-far {}
remaining-to-count to-count]
(if (empty? remaining-to-count)
counted-so-far
(recur (increment-in-map counted-so-far (first remaining-to-count))
(rest remaining-to-count)))))
;(describe
; "counting occurrences"
; (it "empty"
; (should= {} (count-occurrences '())))
; (it "one one"
; (should= {1 1} (count-occurrences '(1))))
; (it "one two"
; (should= {2 1} (count-occurrences '(2))))
; (it "one one, one two"
; (should= {1 1 2 1} (count-occurrences '(1 2)))
; )
; (it "one one, one two, one three"
; (should= {1 1 2 1 3 1} (count-occurrences '(1 2 3))))
; (it "three ones"
; (should= {1 3} (count-occurrences '(1 1 1)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment