Created
June 3, 2011 12:32
-
-
Save gfredericks/1006268 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
(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