发布更新,使其与事件的进程相关(反应和消除杂乱)。
非常感谢您的时间和帮助!
在Clojure的某些早期版本中,每个var都可以使用"binding“表单绑定。现在,如果不将非动态变量定义为动态,就会得到“无法动态绑定非动态变量”。
在某些情况下,在定义后使函数var动态可能是有用的(在测试中使用挂起/模拟)。
不要尝试:
(def ^{:dynamic true} log-call #'log-call)它最终会导致StackOverflowError,因为您正在定义一个调用自己的函数(谢谢您的解释)。
最新问题如下:
所建议的办法似乎行不通。
从绑定表单调用的表单没有定义绑定。
你能帮我找出我错过了什么吗??
以下是更新的代码:
(def all-expenses [{:amount 33.0 :date "today"}
{:amount 44.0 :date "yesterday"}])
(defn fetch-all-expenses [])
(defn fetch-expenses-greater-than [threshold]
(let [all (fetch-all-expenses)]
;calling from a nested form does not see the dynamically bound definition!
(println "2) from fetch-expenses-greater-than:" (fetch-all-expenses))
all))
(defn wrap [f]
(fn [& args] (apply f args)))
(def ^{:dynamic true} fetch-all-expenses (wrap fetch-all-expenses))
(binding [fetch-all-expenses (constantly all-expenses)]
(let [filtered (fetch-expenses-greater-than 15.0)]
(println "1) from inside binding:" (fetch-all-expenses))));calling from binding form OK!在repl中执行该程序的结果是:
2) from fetch-expenses-greater-than: nil
1) from inside binding: [{:date today, :amount 33.0} {:date yesterday, :amount 44.0}]
nil如果我将获取所有费用的定义更改为
(defn ^:dynamic fetch-all-expenses [])结果如预期:
2) from fetch-expenses-greater-than: [{:date today, :amount 33.0} {:date yesterday, :amount 44.0}]
1) from inside binding: [{:date today, :amount 33.0} {:date yesterday, :amount 44.0}]
nil发布于 2013-12-06 21:47:25
非常感谢您的回答@MichałMarczyk。这就解释了。
在使var动态之前使用var的代码:
(def foo 0)
(defn bar []
foo)
(.setDynamic #'foo)
(binding [foo 1]
;; prints foo 1 . bar 0
(println "foo" foo ". bar" (bar)))在使var动态之后使用var的代码:
(def foo 0)
(.setDynamic #'foo)
(defn bar []
foo)
(binding [foo 1]
;; prints foo 1 . bar 1
(println "foo" foo ". bar" (bar)))是的!....with,with-redefs,而不是binding,一切都像预期的那样工作。这正是我所需要的。
https://stackoverflow.com/questions/20415961
复制相似问题