Surprise

5 views
Skip to first unread message

jim

unread,
Mar 7, 2008, 1:09:17 PM3/7/08
to Clojure
I'm poking around with clojure and got a surprise when I typed the
following at the REPL

user=> (def x 19)
#<Var: user/x>
user=> (binding [x x] (def x 1) (println x))
19
nil
user=> x
1

Is this the way it's supposed to work?

Jim

jon

unread,
Mar 7, 2008, 2:00:39 PM3/7/08
to Clojure
Hi, I'm new to clojure too..

> Is this the way it's supposed to work?

Yes.. I'd expect that to modify the root value of the var _outside_ of
the thread-local binding..
See the following comment on http://clojure.sourceforge.net/reference/special_forms.html

"Using def to modify the root value of a var at other than the top
level is usually an indication that you are using the var as a mutable
global, and is considered bad style. Consider either using binding to
provide a thread-local value for the var, or putting a ref or agent in
the var and using transactions or actions for mutation."

This might be what you wanted to achieve.. but I'll let others comment
on when it's appropriate to use (set! ....).

user=> (def x 19)
#<Var: user/x>
user=> (binding [x 1] (println x) (set! x 2) (println x))
1
2
nil
user=> x
19

--Jon

Rich Hickey

unread,
Mar 7, 2008, 2:05:51 PM3/7/08
to Clojure
Yes it is.

binding [x x] creates a thread binding of x and initializes it with
the current value of x (19). def x rebinds the root value of the var x
to 1. println x refers to the value of the thread binding of x (still
19). When binding is done, x no longer has a thread binding, top-level
x refers to root, 1.

def always sets the global root value of a var (vs set!). It is not a
lexical construct, nor a dynamic construct, and its use at other than
the top level should be reserved for defining operations.

See:

http://clojure.sourceforge.net/reference/special_forms.html

Rich

jim

unread,
Mar 7, 2008, 2:31:28 PM3/7/08
to Clojure
That makes sense. The key thing for me to get is that def is not a
lexical construct.
Reply all
Reply to author
Forward
0 new messages