clojure.core/binding¶
binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the supplied initial values, executes the exprs in an implicit do, then re-establishes the bindings that existed before. The new bindings are made in parallel (unlike let); all init-exprs are evaluated before the vars are bound to their new values.
Examples¶
Note by fordsfords¶
The first example (binding mymax to max) appears to be broken. The last line generates the error:
IllegalStateException Can't dynamically bind non-dynamic var: clojure.core/max
I tried inserting (.setDynamic #'max) at the top, and it got rid of the error, but the binding didn't seem to actually happen. I.e. the last line prints 20.
The only way I could get it to work is by redefining max from scratch as dynamic:
(defn ^:dynamic max ([x] x) ([x y] (. clojure.lang.Numbers (max x y))) ([x y & more] (reduce max (max x y) more)))
After THIS the first example succeeds.
The moral of the story - I guess you can't easily bind built-in functions. You need to write your functions with the intention of them being bindable. And I guess the first example should simply be removed?
Note by NeedMoreDesu¶
So about first example --
(defn find-max [x y] (max x y)) ;; => #'user/find-max (binding [max clojure.core/min] (find-max 10 20)) ;; Can't dynamically bind non-dynamic var: clojure.core/max (def ^:dynamic max clojure.core/max) (binding [max clojure.core/min] (find-max 10 20)) ;; => 20 (defn find-max [x y] (max x y)) ;; => #'user/find-max (binding [max clojure.core/min] (find-max 10 20)) ;; => 10
Long story short: var needs to be defined ^:dynamic before you create your function with var being bound here, or else no dynamic building occur (which is intended behavior, I guess).
Note by finalfantasia¶
There's a great blog post from Chas Emerick about binding, Be Mindful of Clojure's binding, that discusses two common pitfalls that one can fall into when using binding.
See also¶
- clojure.core/with-redefs (1)
- clojure.core/with-bindings
- clojure.core/with-local-vars (0)
- clojure.core/def (4)
Content from the matching ClojureDocs page, with authors credited on each contribution.