liveBook · Manning

Lexical binding

As explained in Clojure: The Essential Reference

A local binding associates a name with a value within a limited lexical scope.

Lexical binding creates an accessibility boundary by associating symbols with values inside surrounding parentheses. A binding remains available throughout its lexical scope without being re-evaluated. section 3.1

Clojure local bindings differ from imperative assignment in several important ways:

  • Treat let as syntactic sugar for invoking an anonymous function with immutable parameters. section 3.1
  • Prevent mutation: a bound symbol has no storage location and cannot later produce a different value. section 3.1
  • Allow shadowing, where a later binding reuses a symbol without changing the earlier binding. section 3.1
  • Pass successive local bindings between loop iterations instead of mutating a loop variable. section 3.4

A let binding and its function equivalent

The local symbols a and b exist only inside the expression surrounded by let: (let [a 1 b 2] (* (+ a b) b)) ;; 6. The equivalent anonymous-function form is ((fn [a b] (* (+ a b) b)) 1 2). section 3.1

Figure 3.1. Lexical scope for locally bound symbol "b".
06 lexical scope

Use the scope diagram to trace where a locally bound symbol is visible and why it cannot be resolved after the enclosing expression ends. section 3.1

How Clojure: The Essential Reference covers it

How deep it goes
Explains scope, immutability, shadowing, and let-function equivalence, while stopping short of implementation internals.
Examples
Uses let-to-function equivalence and a loop that passes immutable values to produce squares from zero through nine.
What you can do after
Build local Clojure computations and side-effect-free loops without mutable control variables.
How it connects
Connects lexical scope with anonymous functions, shadowing, recursion, mutation, and functional iteration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.