让我们与Clojure中绑定 [英] Let vs. Binding in Clojure
问题描述
据我所知,他们是不同的,因为一期工程设置 *编译路径*
和一个没有。不过,我需要他们为什么不同的帮助。
I understand that they're different since one works for setting *compile-path*
and one doesn't. However, I need help with why they're different.
让
创建具有给定的绑定一个新的范围,但结合
...
let
creates a new scope with the given bindings, but binding
...?
推荐答案
让
创造一些价值词法范围不变的别名。 结合
创建一个动态范围的一些瓦尔
绑定。
let
creates a lexically scoped immutable alias for some value. binding
creates a dynamically scoped binding for some Var
.
动态绑定意味着你的结合
表格里面的code和任何code这是code调用(即使不在本地词汇范围内)将看到新的绑定。
Dynamic binding means that the code inside your binding
form and any code which that code calls (even if not in the local lexical scope) will see the new binding.
假设:
user> (def ^:dynamic x 0)
#'user/x
结合
实际上创建了一个动态的瓦尔
,但让$ C绑定$ C>只屏蔽了该变种与当地的别名:
binding
actually creates a dynamic binding for a Var
but let
only shadows the var with a local alias:
user> (binding [x 1] (var-get #'x))
1
user> (let [x 1] (var-get #'x))
0
结合
可以使用限定名称和让(因为它在
不能瓦尔
取值时)
binding
can use qualified names (since it operates on Var
s) and let
can't:
user> (binding [user/x 1] (var-get #'x))
1
user> (let [user/x 1] (var-get #'x))
; Evaluation aborted.
;; Can't let qualified name: user/x
让
-introduced绑定是不可变的。 结合
-introduced绑定是线程局部可变:
let
-introduced bindings are not mutable. binding
-introduced bindings are thread-locally mutable:
user> (binding [x 1] (set! x 2) x)
2
user> (let [x 1] (set! x 2) x)
; Evaluation aborted.
;; Invalid assignment target
词汇和动态绑定:
Lexical vs. dynamic binding:
user> (defn foo [] (println x))
#'user/foo
user> (binding [x 1] (foo))
1
nil
user> (let [x 1] (foo))
0
nil
这篇关于让我们与Clojure中绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!