Created
March 28, 2010 01:52
-
-
Save ato/346494 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(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