开发者

What's the difference between var and quote?

What's meaning difference between var and quote in Clojure? For example, (var a) and (quote a).

The official site has the below documents, but what's the difference of var object and the value for the symbol? I am confused.

(var symbol) The symbol must resolve to a var, and the Var ob开发者_Python百科ject itself (not its value) is returned


(quote a) returns a symbol (clojure.lang.Symbol) - it effectively does the same as 'a. It's worth reading a bit more about the Clojure reader to find out a bit more about symbols. Example:

(quote a)
=> a

(var a) returns the var (clojure.lang.Var) represented by the symbol a in the current namespace. You'll get an error if a is not defined in the current namespace. Example:

(var a)
=> #<CompilerException java.lang.RuntimeException: Unable to resolve var: a in this context, compiling:(NO_SOURCE_PATH:1)>

(def a 1)
(var a)
=> #'user/a

That's the technical definition - but here's the intuition behind it: a symbol is a name, which can be used to look up a var in a given namespace. A var itself is a kind of reference that can hold any kind of Clojure value. So a symbol identifies a var which contains a value.


Consider this:

; #'x a reader short-cut for (var x), and 'x is a short-cut for (quote x)
(def x)
(binding [x 1] (var-set #'x 2) (list (var x) (quote x) x)) 

Which evaluates to something like (comments added)

(
 #'sandbox177857/x ; the variable itself - was passed to var-set
 x                 ; the symbol x. same as 'x
 2                 ; last value in #'x
)

set! will take in (among other things) a Var or a symbol which resolves to a global name (var-set will only accept a Var). The reason why (var-set x ...) wouldn't have worked is that this would have resulted in the value of x being passed in (and not the Var called x).

Hope this helped. Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜