4
votes

I am trying to understand the clojure notion of a Var.

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)

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

1

1 Answers

6
votes

Yup that is a fine notion of it. I would adjust your final statement slightly: #'v expands to (var v), it doesn't make sense to say var (var v), instead I would say just var v. Also I would say derefs to the value 7 instead of points to. Yes they behave like pointers, but they have a special deref (or @) form to dereference them (and you can't do pointer arithmatic).

I think adopting the term deref is important in understanding another aspect of Clojure: When you use any symbol, say we make a function call (inc 1), there is actually a hidden step! inc is a symbol which is associated with the var inc, (inc is not really a function! inc just derefs to a function) but then evaluated vars automatically deref. When you write (var inc), you are actually just preventing that deref. That is why when you alter or replace a var, say we redefined inc, the new code gets executed.

The point is, when thinking in terms of pointers, you may be tempted to think of inc as the function that some var is pointing to. This is not correct. inc is symbol associated with the var that derefs to a function. When using the var inc, it automatically resolves to the function for convenience. In this sense you could argue that just saying v derefs to the value 7 is accurate. v is a var, you don't really need to specify it. (Obviously it makes sense to when you are trying to explicitly point out that it is a var, so calling it a var isn't wrong either).