Clojure Vars 与其他语言中的指针/引用

Geo*_*rge 4 clojure

我试图理解Var的 clojure 概念。

As far as I can tell, it's just a reference/pointer to a value. The "root value" of a Var can be thought of as the initial value that a Var points to on a thread. Moreover, I take it that -- behind the scenes -- every Var has an address to the position in memory it is pointing towards (even though languages like Java, Javascript don't give you access to that particular location, and perhaps do things behind the scenes that make that address unstable anyway).

Question: Is this the right way to think about it? In what ways is it wrong to think of a clojure Var as a reference/pointer to a value?

Given something like

(def v 7)
Run Code Online (Sandbox Code Playgroud)

Is it appropriate to say things like "the Var #'v points to the value 7"?

Tim*_*ley 6

是的,这是一个很好的概念。我会稍微调整一下你的最终陈述: #'v扩展为(var v),说 var (var v) 没有意义,相反我会说只是 var v。另外我会说derefs值 7 而不是指向。是的,它们的行为类似于指针,但是它们有一个特殊的deref(或@)形式来取消引用它们(并且您不能进行指针算术运算)。

我认为采用这个术语deref对于理解 Clojure 的另一个方面很重要:当你使用任何符号时,比如我们进行函数调用(inc 1),实际上有一个隐藏的步骤!inc是一个与 var 相关联的符号inc,(inc实际上不是一个函数!inc只是解引用到一个函数)但随后会自动评估 vars deref。当您编写 (var inc) 时,您实际上只是在防止deref. 这就是为什么当你改变或替换一个 var 时,比如 we redefined inc,新代码会被执行。

关键是,当考虑指针时,您可能会倾向于将 inc 视为某个 var 指向的函数。这是不正确的。inc 是与解除引用函数的 var 相关联的符号。使用 var inc 时,为方便起见,它会自动解析为该函数。从这个意义上说,您可能会争辩说,仅将 v derefs 指向值 7 是准确的。v 是一个 var,你真的不需要指定它。(显然,当您试图明确指出它是一个 var 时,这是有意义的,因此将其称为 var 也没有错)。