Let vs Binding in Clojure

I understand that they are different from each other, since one works to install *compile-path* , and the other does not. However, I need help on why they are different.

let creates a new scope with the given bindings, but binding ...?

+65
let clojure binding
Oct. 06 '09 at 1:50
source share
3 answers

let creates a lexically modified alias for some value. binding creates a dynamic-binding binding for some Var .

Dynamic binding means that the code inside your binding form and any code that calls this code (even if not in the local lexical area) will see a new binding.

Given:

 user> (def ^:dynamic x 0) #'user/x 

binding actually creates a dynamic binding for Var , but let only a shadow of var with a local alias:

 user> (binding [x 1] (var-get #'x)) 1 user> (let [x 1] (var-get #'x)) 0 

binding can use qualified names (since it works on Var s) and let cannot:

 user> (binding [user/x 1] (var-get #'x)) 1 user> (let [user/x 1] (var-get #'x)) ; Evaluation aborted. ;; Can't let qualified name: user/x 

let integrated bindings are not changed. binding integrated bindings change by type:

 user> (binding [x 1] (set! x 2) x) 2 user> (let [x 1] (set! x 2) x) ; Evaluation aborted. ;; Invalid assignment target 

Lexical and dynamic linking:

 user> (defn foo [] (println x)) #'user/foo user> (binding [x 1] (foo)) 1 nil user> (let [x 1] (foo)) 0 nil 

See also Vars , let .

+99
Oct 06 '09 at 3:00
source share
β€” -

Another syntax difference for let vs binding:

For binding, all initial values ​​are calculated before any of them are bound to vars. This is different from let, where you can use the value of the previous β€œalias” in the subsequent definition.

 user=>(let [x 1 y (+ x 1)] (println y)) 2 nil user=>(def y 0) user=>(binding [x 1 y (+ x 1)] (println y)) 1 nil 
+10
Nov 11 2018-10-11T00:
source share

binding binds a value to a name in the global environment for each thread

As you already mentioned, let creates a new scope for the specified bindings.

+8
Oct 06 '09 at 2:16
source share



All Articles