The story of Clojure Var's - part 2
May 15, 2010
Clojure `vars' have many other interesting features. For example, in the code snippet given below:
(def k 10) (defn foo [] (binding [k 2] (+ k 3))) ; returns 5
We are `binding' the var k to value 2 within function `foo' - this is completely different from doing `(def k 2)' within `foo' because we are now assigning a different value for the var `k' which is visible only within function `foo' - this `binding' does not in any way affect the global, `root binding' of the var, which still remains as 10.
Bindings have `dynamic scope'. Let's find out what this means.
(def k 10) (defn fun1 [] (+ k 5)) (defn fun2 [] (binding [k 100] (fun1))) ; returns 105
In a statically scoped language, function `fun1' should always return 15, whether it is called directly or from some other function. But we see that when `fun1' is called from `fun2' (after having created a new binding for k), it sees 100 as the value for `k'. This shows that bindings have dynamic scope.
A `var' need not always have a root binding; thus, you can do:
(def T) ; (+ T 2) will not work - no value for T (defn foo [] (binding [T 10] (+ T 2))) ; returns 12
[Go to Code Clojure home] [Follow me on Twitter] [Go to pramode.net home]