Updating multiple Clojure atom elements in a single swap statement?

I have an atom that has two parts.

(def thing (atom {:queue '() :map {}})) 

I want to update both: queue and: map in one atomic clock cycle to prevent them from syncing.

Queue separately:

 (swap! thing update-in [:queue] (list 1)) 

(From this question: How to add to a nested list in a Clojure atom? )

Card individually:

 (swap! thing assoc-in [:map 1] (:key :value)) 

(From this question: Using swap for MERGE (adding to) a nested map in a Clojure atom? )

How can I do this as in a single swap statement? (assuming this will prevent them from getting out of sync?)

+7
clojure
source share
2 answers

You have one change you want to make, right? And can you write this change as a pure function? All you have to do is write this function and pass it as a swap! argument swap! .

 (defn take-from-queue [{q :queue, m :map}] {:queue (rest q), :map m (assoc m :new-task (first q))}) (swap! thing take-from-queue) 

Where, of course, I have no idea that you really want the body of your function to be executed, so I made up what does not throw an exception.

+9
source share

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.

0
source share

All Articles