什么时候应该使用交换或重置 [英] When should you use swap or reset

查看:78
本文介绍了什么时候应该使用交换或重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure函数中使用 swap! reset!有什么区别?我从clojure.core文档中看到它们用于更改原子的值,但是我不确定何时使用 swap!和何时使用重置!

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!.

在什么情况下会使用交换!情况下您会使用 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))}]

上面的代码是使用 reset!作为按钮的示例

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)}]

此按钮使用 swap!

交换!重置!可以互换吗?

谢谢

推荐答案

swap!使用函数来修改原子的值。当原子的当前值很重要时,通常将使用 swap!。例如,增加值取决于当前值,因此可以使用 inc 函数。

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!只是将原子的值设置为一些新值。通常,当您只想设置值而不关心当前值是什么时。

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

这篇关于什么时候应该使用交换或重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆