What is the atom reset method in Clojure?
What is an atom?
In Clojure, all variables are immutable except for the agent and atom, which are methods that allow variables to change their state. An atom in Clojure is a datatype that handles the sharing and synchronizing of the Clojure independent state as Clojure data structures are immutable.
What is the reset method?
The reset method updates the value of an atom without considering the old one.
Syntax
(reset! nameofAtom value)
Syntax of the reset method
Parameter
From the syntax above, we can see that the reset method uses two parameters:
nameofAtom: Theatomwe want to update.value: The new value of the atom.
Return value
The reset method returns atom with a new value.
Code
Let's see an example:
(ns clojure.examples.example(:gen-class))(defn func [](def atomm (atom 1))(println @atomm)(reset! atomm 2)(println @atomm))(func)
Explanation
- Line 3: We create a function
func.
- Line 4: We set the value of the variable
atommto1using anatom.
- Line 5: We print the value of
atomm.
- Line 6: We use the
resetmethod to change the value to2.
- Line 7: We print the new value of
atomm.
- Line 8: We call the function
func.