ClojureDocs

Nav

Namespaces

atom

clojure.core

Available since 1.0 (source)
  • (atom x)
  • (atom x & options)
Creates and returns an Atom with an initial value of x and zero or
more options (in any order):
 :meta metadata-map
 :validator validate-fn
 If metadata-map is supplied, it will become the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception.
5 Examples
user=> (def my-atom (atom 0))
#'user/my-atom

user=> @my-atom
0

user=> (swap! my-atom inc)
1

user=> @my-atom
1

user=> (swap! my-atom (fn [n] (* (+ n n) 2)))
4

user=> (reset! my-atom 0)
0

user=> @my-atom
0
user=> (def a (atom #{}))
#'user/a

user=>(swap! a conj :tag)
#{:tag}

user=> @a
#{:tag}
user=> (def my-atom (atom 0 :validator even?))
#'user/my-atom

user=> @my-atom
0

user=> (swap! my-atom inc)
IllegalStateException Invalid reference state  clojure.lang.ARef.validate (ARef.java:33)

user=> (swap! my-atom (partial + 2))
2

user=> @my-atom
2
(def car
  (atom {:make "Audi"
         :model "Q3"}))

@car
;;{:make "Audi", :model "Q3"}

(swap!
 car
 assoc :model "Q5")
;;{:make "Audi", :model "Q5"}

(reset! car {:make "" :model ""})
;;{:make "", :model ""}
(defn atom? [v]
  #?(:clj  (instance? clojure.lang.Atom v)
     :cljs (satisfies? cljs.core/IAtom v)))

(atom? (atom nil)) ;; => true
See Also

Sets the value of atom to newval without regard for the current value. Returns newval.

Added by kumarshantanu

Atomically swaps the value of atom to be: (apply f current-value-of-atom args). Note that f may be...

Added by kumarshantanu

Atomically sets the value of atom to newval if and only if the current value of the atom is identi...

Added by johnnyluu

Adds a watch function to an agent/atom/var/ref reference. The watch fn must be a fn of 4 args: a k...

Added by eric

Removes a watch (set by add-watch) from a reference

Added by eric

Sets the validator-fn for a var/ref/agent/atom. validator-fn must be nil or a side-effect-free fn ...

Added by kumarshantanu

Atomically swaps the value of atom to be: (apply f current-value-of-atom args). Note that f may be...

Added by agarman

Sets the value of atom to newval. Returns [old new], the value of the atom before and after the r...

Added by agarman

Must be called in a transaction. Sets the value of ref. Returns val.

Added by ghoseb
0 Notes
No notes for atom