mbrodersen wrote: > In this simple recursive expression: > > (def t (fn [x] (if (zero? x) 0 (+ x (t (dec x)))))) > > The fn special form is evaluated within a context where t is not yet > bound. > > t is only bound AFTER fn has captured its environment. > > In other words, the closure captured by fn doesn't know anything about > t (or maybe only that t is unbound). > > And yet it still works if I call t: > > (t 5) => 15 > > My question is how Clojure ensures that t is bound to the closure > after the closure has already been captured?
t is a var. The var is created before the body of def is evaluated. At that point it is unbound. The function closes over the var not the value of the binding. That's why you can re-evaluate a function, changing it's behaviour, without having to re-evaluate everything that calls it. You'll notice that with locals (which aren't vars, they're immutable) it doesn't work: (let [t (fn [x] (if (zero? x) 0 (+ x (t (dec x)))))] (t 2)) Also if you try to use the var in the bindings you'll get an unbound error, not an unable to resolve symbol error: (def foo foo) -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en