Skip to content

Instantly share code, notes, and snippets.

@trickyBytes
Last active November 18, 2015 09:41
Show Gist options
  • Save trickyBytes/883548a7a17cf47141cb to your computer and use it in GitHub Desktop.
Save trickyBytes/883548a7a17cf47141cb to your computer and use it in GitHub Desktop.
Using atoms in Clojure
;A map stored in an atom
(def register (atom {}))
;An item to register
(defrecord register-item [item-name time-added])
(defn addSomethingToRegister [item-name register]
;Do the following inside a let
(let
;create new register-item and assing to ref item
[item (->register-item item-name (Date.))]
;create a new map by adding the new item to the existing register map
;use swap to replace the map inside the register atom
(swap! register #(assoc % (:item-name item) item))
; return the created item - last expresion inside the let is always returned
item))
;To use it
(addSomethingToRegister "1" register)
@trickyBytes
Copy link
Author

A little example of using atoms in clojure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment