Difference between binding and binding
3 answers
with bindings is useful when you need to dynamically choose what to bind . here's a fun example where we arbitrarily choose what to bind:
user> (def ^:dynamic a)
#'user/a
user> (def ^:dynamic b)
#'user/b
user> (binding [a 1
b 2]
(+ a b))
3
user> (with-bindings (if (rand-nth [true false])
{#'a 1
#'b (rand-int 10)}
{#'a 1
#'b 2})
(+ a b))
3
user> (with-bindings (if (rand-nth [true false])
{#'a 1
#'b (rand-int 10)}
{#'a 1
#'b 2})
(+ a b))
3
user> (with-bindings (if (rand-nth [true false])
{#'a 1
#'b (rand-int 10)}
{#'a 1
#'b 2})
(+ a b))
1
if you try it with with bind
it will get frustrated that it didn't pass a literal vector as an anchor shape.
user> (binding (if (rand-nth [true false])
{#'a 1
#'b (rand-int 10)}
{#'a 1
#'b 2})
(+ a b))
IllegalArgumentException binding requires a vector for its binding in user:138 clojure.core/binding (core.clj:1865)
+7
source to share