Skip to content

Instantly share code, notes, and snippets.

@aria42
Created September 19, 2010 18:53
Show Gist options
  • Save aria42/587011 to your computer and use it in GitHub Desktop.
Save aria42/587011 to your computer and use it in GitHub Desktop.
;; Counter: Map from object to value, cache total
(defrecord Counter [counts total])
(defn get-count
"retrieve count of k from counter, should not be negative"
[counter k]
{:post [(not (neg? %))]}
(get (:counts counter) k 0.0))
(defn inc-count
"increment-count of k in counter by weight amount"
[counter k weight]
(let [new-count (+ (get-count counter k) weight)]
(Counter. (if (zero? new-count)
(dissoc (:counts counter) k)
(assoc (:counts counter) k new-count))
(+ (:total counter) weight))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment