Say you have a hash map:
(def m1 (atom {:a "A" :b "B"}))
To change :a and :b at the same time, changing their values ββto different values, for example, numbers 1 and 2, use this function:
(defn my-swap! [params] (swap! m1 (fn [old new] new) params))
So:
(my-swap! {:a 1 :b 2}) ;=> {:a 1, :b 2}
And the same effect can be achieved using the following function and execution:
(defn my-multi-swap! [params1 params2] (swap! m1 (fn [old new1 new2] new2) params1 params2)) (my-multi-swap! {} {:a 1 :b 2}) ;=> {:a 1, :b 2}
Usually reset! used if you want to ignore the old value. Here we use it:
(defn my-merge-swap! [params] (swap! m1 (fn [old new] (merge old new)) params)) (my-merge-swap! {:b 3}) ;=> {:a "A", :b 3}
The first parameter to swap! function is the existing value of the atom, and you must pass one or more additional parameters that you can use to give the atom its new value.
Chris murphy
source share