Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

clojure - When should you use swap or reset

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 value of an atom but I am not sure when to use swap! and when to use reset!.

What circumstances would you use swap! and which circumstances would you use reset!?

[:input {:type "text"
         :value @time-color
         :on-change #(reset! time-color (-> % .-target .-value))}]

The above code is an example of using reset! for a button

[:input.form-control
          {:type      :text
           :name      :ric
           :on-change #(swap! fields assoc :ric (-> % .-target .-value))
           :value     (:ric @fields)}]

And this button uses swap!

Are swap! and reset! interchangeable?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...