for* is the sequential counterpart to for, evaluating both loop initializers and step updates sequentially from top to bottom.
Syntax
(for* ⟨label⟩? (⟨binding-or-declare⟩*)
[:returns ⟨return-expr⟩]
[{:while | :until | :repeat} ⟨termination-expr⟩]
⟨body-element⟩*)
;; ⟨label⟩ := :⟨keyword-name⟩
;; ⟨binding-or-declare⟩ := (⟨var⟩ ⟨init-expr⟩ ⟨step-expr⟩)
;; | (declare ⟨var⟩ ⟨qualified-type⟩)
Semantics
for*has the same clause structure,:returnsbehavior, termination clauses (:while,:until,:repeat), and loop-label rules asfor, with sequential binding and step evaluation:- Sequential initializers: Each
⟨init-expr⟩is evaluated top-to-bottom (viacl:let*), so later initializers can reference earlier loop variables, and initializers cannot reference their own or later loop variables. - Sequential steps: At the end of each iteration,
⟨step-expr⟩forms are evaluated and assigned top-to-bottom (viacl:setq), so each⟨step-expr⟩observes the already-updated values of earlier bindings in the list.
- Sequential initializers: Each
- Duplicate binding variable names in the same
for*binding list are rejected at compile time. :returns ⟨return-expr⟩, if supplied, must appear immediately after the binding list; when omitted,for*returnsVoid(zero values).
Examples
;; `acc` step uses the already-incremented value of `i` in the same iteration
(coalton
(for* ((declare i Integer)
(declare acc Integer)
(i 0 (+ i 1))
(acc 0 (+ acc i)))
:returns acc
:until (== i 5)))
; => 15
Other Notes
- Contrast the step phase of
for*withfor: in(for ((i 0 (+ i 1)) (acc 0 (+ acc i))) ...),(+ acc i)adds the old value ofifrom before the step (0 + 1 + 2 + 3 + 4 = 10), whereas infor*above,iis updated to(+ i 1)first and(+ acc i)adds the new value ofi(1 + 2 + 3 + 4 + 5 = 15). - In release mode, a local
coalton/cell:Cellaccumulator created withcell:newand mutated or read inside afor*loop is unboxed into a typed mutable lexical variable when theCelldoes not escape its defining function. See Performance and Optimization.