Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between binding and with-bindings

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.

like image 261
Dr Ljotsson Avatar asked Nov 28 '25 11:11

Dr Ljotsson


1 Answers

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)
like image 52
Arthur Ulfeldt Avatar answered Dec 01 '25 05:12

Arthur Ulfeldt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!