January 2014
Intermediate to advanced
232 pages
5h 11m
English
Clojure provides support for declaring dynamic variables that can have their value changed within a particular scope. Let’s look at how this works.
| | (declare ^{:dynamic true} *foo*) |
| | (println *foo*) |
| | =>#<Unbound Unbound: #'bar/*foo*> |
Here we declared *foo* as a dynamic Var and didn’t provide any value for it. When we try to print *foo* we get an error indicating that this Var has not been bound to any value.
Let’s look at how we can assign a value to *foo* using a binding.
| | (defn with-foo [f] |
| | (binding [*foo* "foo"] |
| | (f))) |
| | (with-foo #(println *foo*)) |
| | =>foo |
We set *foo* to a string with value "foo" inside our with-foo function. When our anonymous function is called inside with-foo we no longer get an error ...
Read now
Unlock full access