Clojure中with-local-vars和with-bindings之间的区别

时间:2013-08-28 17:50:21

标签: clojure dynamic-binding

Clojure with-local-varswith-bindings的文档不足以让我区分这两者。任何提示?

2 个答案:

答案 0 :(得分:11)

var临时创建新的with-local-vars。现有var暂时被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...

答案 1 :(得分:2)

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

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