Difference between with-local-vars and with-bindings in Clojure

狂风中的少年 提交于 2019-12-09 16:50:13

问题


The documentation for Clojure with-local-vars and with-bindings doesn't suffice for me to distinguish the two. Any hints?


回答1:


New vars are temporarily created by with-local-vars. Existing vars are temporarily rebound by with-bindings. In both cases the bindings are thread-local.

Note that with-bindings is, as far as I can tell, primarily useful as a helper to pass bindings from another context by using a map returned by get-thread-bindings. The similar function binding would be more typical when not importing bindings.

Illustrative examples:

(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...



回答2:


(with-bindings) expects the keys of the bindings map to be Vars, not symbols. It pushes the given map of var/values onto the stack of thread local bindings and take care to remove it after the given function returned. It is a low level function.

(with-local-vars) allows you to code in imperative style (mutating state).



来源:https://stackoverflow.com/questions/18494860/difference-between-with-local-vars-and-with-bindings-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!