Let vs. Binding in Clojure

BindingClojureLet

Binding Problem Overview


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...?

Binding Solutions


Solution 1 - Binding

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.

Solution 2 - Binding

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

Solution 3 - Binding

binding binds a value to a name in the per-thread global environment

As you mentioned, let creates a new scope for said bindings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarlView Question on Stackoverflow
Solution 1 - BindingBrian CarperView Answer on Stackoverflow
Solution 2 - BindingMarcView Answer on Stackoverflow
Solution 3 - BindingYuval AdamView Answer on Stackoverflow