In this guide, we will discuss Clojure Atoms compare-and-set! Atomically sets the value of atom to the new value if and only if the current value of the atom is identical to the old value held by the atom. Returns true if set happens, else it returns false.
Syntax
Following is the syntax.
(compare-and-set! atom-name oldvalue newvalue)
Parameters − ‘atom-name’ is the name of the atom whose value needs to be reset. ‘oldvalue’ is the current old value of the atom. ‘newvalue’ is the new value which needs to be assigned to the atom.
Return Value − The atom with the new value will be set only if the old value is specified properly.
Example
An example on how this is used is shown in the following program.
(ns clojure.examples.example (:gen-class)) (defn example [] (def myatom (atom 1)) (println @myatom) (compare-and-set! myatom 0 3) (println @myatom) (compare-and-set! myatom 1 3) (println @myatom)) (example)
Output
The above program will produce the following output.
1 1 3
Next Topic : Click Here
Pingback: Clojure - Atoms reset! | Adglob Infosystem Pvt Ltd
Pingback: Clojure - Atoms | Adglob Infosystem Pvt Ltd