Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let vs. Binding in Clojure

I understand that they're different since one works for setting *compile-path* and one doesn't. However, I need help with why they're different.

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

like image 487
Carl Avatar asked Oct 06 '09 01:10

Carl


2 Answers

let creates a lexically scoped immutable alias for some value. binding creates a dynamically scoped binding for some Var.

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

Given:

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

binding actually creates a dynamic binding for a Var but let only shadows the 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 operates on Vars) and let can't:

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-introduced bindings are not mutable. binding-introduced bindings are thread-locally mutable:

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

Lexical vs. dynamic binding:

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.

like image 160
Brian Carper Avatar answered Sep 17 '22 17:09

Brian Carper


One more syntactic difference for let vs binding:

For binding, all the initial values are evaluated before any of them are bound to the vars. This is different from let, where you can use the value of a previous "alias" in a 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 
like image 36
Marc Avatar answered Sep 21 '22 17:09

Marc