What is the difference between the Clojure functions binding and with-bindings? They seem to do the exact same thing but with slightly different syntax.
with-bindings is useful when you need to dynamically choose what to bind. here's a fun example where we randomly 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 that with bind it will be upset about not being passed a literal vector as the binding form.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With