What is the difference between using swap!
and reset!
in Clojure functions? I have seen from the clojure.core docs that they are used to change the
swap!
uses a function to modify the value of the atom. You will usually use swap!
when the current value of the atom matters. For example, incrementing a value depends on the current value, so you would use the inc
function.
reset!
simply sets the value of the atom to some new value. You will usually use this when you just want to set the value without caring what the current value is.
(def x (atom 0))
(swap! x inc) ; @x is now 1
(reset! x 100) ; @x is now 100
(swap! x inc) ; @x is now 101