Skip to content

Instantly share code, notes, and snippets.

@alexy
Forked from ato/autoincrementmap.clj
Created March 28, 2010 03:07
Show Gist options
  • Save alexy/346534 to your computer and use it in GitHub Desktop.
Save alexy/346534 to your computer and use it in GitHub Desktop.
(defn assoc-autoinc [m k]
(if (get m k)
m
(let [v (inc (:last-value (meta m) -1))]
(with-meta
(assoc m k v)
(assoc (meta m) :last-value v)))))
(defn get-or-autoinc! [m k]
(if-let [v (get @m k)]
v
(get (swap! m assoc-autoinc k) k)))
;;
;; Alternative version: just based on count
;;
(defn assoc-autoinc [m k]
(if (get m k)
m
(assoc m k (count m))))
;;;; Example usage
(def mymap (atom {}))
@mymap ; => {}
(get-or-autoinc! mymap :foo) ; => 0
(get-or-autoinc! mymap :bar) ; => 1
(get-or-autoinc! mymap :foo) ; => 0
(get-or-autoinc! mymap :baz) ; => 2
@mymap ; => {:baz 2, :bar 1, :foo 0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment