3
votes

I know that in Clojure, namespaces map symbols to Vars. So we can map the symbol x to a Var (here in the default namespace) like this:

user=> (def x 5)
#'user/x
user=> #'x
#'user/x
user=> (type #'x)
clojure.lang.Var    
user=> x
5

Now if I subsequently say this

user=> (def x 3)
#'user/x

Have I rebound the symbol x to a brand new Var or have I updated the value in the same Var I created above? How would I know?

I'm thinking it's the latter because I read the sentence "Only Java fields, Vars, Refs and Agents are mutable in Clojure." in the Clojure Reference page on Vars but I'm not sure that holds as a proof.

2
Your hunch seems confirmed in this question: stackoverflow.com/questions/16447621/… - jmargolisvt
Good find.... I was hoping there was something like a Python or Ruby id, though. - Ray Toal

2 Answers

3
votes

No, def does not always create a new Var. You can confirm this using identical?:

user=> (def x 5)
#'user/x
user=> (def v #'x)
#'user/v
user=> (def x 3)
#'user/x
user=> (identical? v #'x)
true
3
votes

Elogent's answer is excellent and accepted, but I just found another way to prove that a new var is not created, which might be of use:

user=> (def x 10)
#'user/x
user=> (let [y #'x] (println @y) (def x 7) (println @y))
10
7
nil

If def did create a new var, we would have seen 10 printed twice.