When should you use swap or reset

前端 未结 1 1392
感动是毒
感动是毒 2020-12-18 22:09

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

相关标签:
1条回答
  • 2020-12-18 22:23

    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
    
    0 讨论(0)
提交回复
热议问题