8

Clojure 的文档with-local-varswith-bindings不足以让我区分两者。有什么提示吗?

4

2 回答 2

11

Newvar是由 临时创建的with-local-vars。现有vars 暂时反弹with-bindings。在这两种情况下,绑定都是线程本地的。

请注意,with-bindings据我所知,它主要用作帮助器,通过使用返回的映射从另一个上下文传递绑定get-thread-bindings。当不导入绑定时,类似的功能binding会更典型。

说明性示例:

(binding [*out* (new java.io.StringWriter)] 
  (print "world!") (str "hello, " *out*))
;=> "hello, world!"

(with-local-vars [*out* (new java.io.StringWriter)] 
  (print "world!") (str "hello," *out*))
;=> world!"hello,#<Var: --unnamed-->"

(with-local-vars [foo (new java.io.StringWriter)] 
  (.write @foo "world") (str "hello, " @foo))
;=> "hello, world"

(binding [foo (new java.io.StringWriter)] 
  (.write @foo "world") (str "hello, " @foo))
;=> CompilerException java.lang.RuntimeException: 
;     Unable to resolve var: foo in this context...
于 2013-08-28T18:16:04.803 回答
2

(with-bindings) 期望绑定映射的键是 Vars,而不是 symbols。它将给定的 var/values 映射推送到线程本地绑定的堆栈上,并在给定函数返回后注意将其删除。这是一个低级功能。

(with-local-vars) 允许您以命令式风格(变异状态)进行编码。

于 2013-08-28T18:17:04.817 回答