let* introduces lexical bindings sequentially from top to bottom.
Syntax
(let* (⟨binding-or-declare⟩*)
⟨body-element⟩*
⟨expr⟩)
;; ⟨binding-or-declare⟩ := (⟨var⟩ ⟨init-expr⟩)
;; | (declare ⟨var⟩ ⟨qualified-type⟩)
Semantics
let*evaluates and binds(⟨var⟩ ⟨init-expr⟩)clauses strictly in top-to-bottom source order.- Each
⟨init-expr⟩sees bindings introduced earlier in thelet*list, but does not see its own binder or later binders (bindings inlet*are non-recursive). - Duplicate variable names within the same
let*binding list are rejected at compile time. - Each
(⟨var⟩ ⟨init-expr⟩)must produce a single value; to destructure patterns or multiple values sequentially in a body, use shorthand(let ⟨pattern⟩ = ⟨expr⟩)or(let (values ...) = ⟨expr⟩)(seelet). - Local
declareforms in the binding list constrain the named bindings. - The body is an implicit
progn(supporting multiple expressions and shorthandletbindings), and its final expression is in tail position when thelet*is in tail position.
Examples
(coalton
(let* ((declare x Integer)
(x 10)
(y (* x 2))
(z (+ x y)))
z))
; => 30
Other notes
- Non-escaping local functions bound by
let*are declareddynamic-extent, allowing the Lisp compiler to stack-allocate their closures. - In release mode, a locally bound
coalton/cell:Cellcreated withcell:newthat does not escape its lexical scope is unboxed into a typed mutable lexical variable with no heap allocation. See Performance and Optimization. - Use
letwhen defining recursive or mutually recursive local functions.