Skip to content

Instantly share code, notes, and snippets.

@gfredericks
Created June 3, 2011 12:32
Show Gist options
  • Save gfredericks/1006268 to your computer and use it in GitHub Desktop.
Save gfredericks/1006268 to your computer and use it in GitHub Desktop.
(let [a (atom 1)]
(defn generate-unique-id
"Returns the next value of a thread-safe incrementing variable."
[]
(swap!
a
#(inc %))))
;; if we use (def) instead of (defn), we can move the atom variable inside the
;; (def) form. We just have to make sure that the atom is only created once, at
;; the beginning, and not every time the function is called.
(def generate-unique-id
(let [a (atom 1)]
(fn [] (swap! a #(inc %)))))
;; #(inc %) is the same as inc itself
(def generate-unique-id
(let [a (atom 1)] (fn [] (swap! a inc))))
;; passing the atom to (partial), which will curry the swap! function, will work too
(def generate-unique-id
(partial swap! (atom 1) inc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment