gpt4 book ai didi

clojure - :key parameter in add-watch function是什么意思

转载 作者:行者123 更新时间:2023-12-04 16:31:34 24 4
gpt4 key购买 nike

我的问题是,通过提供的文档和示例,我无法理解 :key 的含义参数或其可能的值
这是我所指函数的官方文档页面:
http://clojuredocs.org/clojure_core/clojure.core/add-watch

add-watch clojure.core

(add-watch reference key fn)  

Adds a watch function to an agent/atom/var/ref reference. The watch fn must be a fn of 4 args: a key, the reference, its old-state, its new-state. Whenever the reference's state might have been changed, any registered watches will have their functions called. The watch fn will be called synchronously, on the agent's thread if an agent, before any pending sends if agent or ref. Note that an atom's or ref's state may have changed again prior to the fn call, so use old/new-state rather than derefing the reference. Note also that watch fns may be called from multiple threads simultaneously. Var watchers are triggered only by root binding changes, not thread-local set!s. Keys must be unique per reference, and can be used to remove the watch with remove-watch, but are otherwise considered opaque by the watch mechanism.



谢谢

最佳答案

它基本上只是一个标识符,您可以在调用代码时使用它来识别 watch ,以防每个引用有多个 watch 。它应该对您的应用程序代码具有重要意义,但会被 Clojure 传递。

例如:

user> (def a (atom 0))
#'user/a
user> (add-watch a
:count-to-3
(fn [k r old-state new-state]
(println "changed from" old-state "to" new-state)
(when (>= new-state 3)
(remove-watch a :count-to-3))))
#<Atom@3287a10: 0>
user> (dotimes [_ 5] (swap! a inc))
changed from 0 to 1
changed from 1 to 2
changed from 2 to 3
nil
user> @a
5

关于clojure - :key parameter in add-watch function是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20153796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com