Clojure - Atoms swap!


Advertisements

Atomically swaps the value of the atom with a new one based on a particular function.

Syntax

Following is the syntax.

(swap! atom-name function)

Parameters − ‘atom-name’ is the name of the atom whose value needs to be reset. ‘function’ is the function which is used to generate the new value of the atom.

Return Value − The atom with the new value will be set based on the function provided.

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)
   
   (swap! myatom inc)
   (println @myatom))
(example)

Output

The above program produces the following output.

1
2

From the above program you can see that the ‘inc’ (Increment function) is used to increment the value of the atom and with the help of the swap! function, the new value is automatically associated with the atom.

clojure_atoms.htm
Advertisements