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

2024-05-06

Clojure 的文档with-local-vars http://clojuredocs.org/clojure_core/clojure.core/with-local-vars and with-bindings http://clojuredocs.org/clojure_core/clojure.core/with-bindings不足以让我区分两者。有什么提示吗?


New vars 是临时创建的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...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Clojure 中 with-local-vars 和 with-bounds 之间的区别 的相关文章

随机推荐