break exits an enclosing for or for* loop immediately.
Syntax
;; Exit the innermost enclosing loop
(break)
;; Exit a labeled enclosing loop
(break ⟨label⟩)
;; ⟨label⟩ := :⟨keyword-name⟩
Semantics
(break)exits the innermost enclosingfororfor*loop;(break ⟨label⟩)exits the enclosing loop named by keyword⟨label⟩.breakmust appear lexically inside the body of the targetfororfor*loop within the same function:- It cannot appear in the loop’s binding initializers, step expressions,
:returnsexpression, or termination condition. - It cannot cross an anonymous
fnboundary to exit a loop outside thatfn.
- It cannot appear in the loop’s binding initializers, step expressions,
- When
breakexecutes:- The current iteration’s step expressions are skipped.
- Control transfers to the end of the target loop, which then evaluates and returns its
:returnsexpression (or returnsVoidif:returnswas omitted).
- A
breakexpression itself has typeVoid(zero values).
Examples
;; Break out of a loop early and return the current loop binding
(coalton
(for ((declare i Integer)
(i 0 (+ i 1)))
:returns i
:while (< i 100)
(when (== (* i i) 49)
(break))))
; => 7
;; Break out of an outer labeled loop from an inner loop
(coalton
(progn
(let found = (coalton/cell:new None))
(for :rows ((r 0 (+ r 1)))
:while (< r 4)
(for ((c 0 (+ c 1)))
:while (< c 4)
(when (and (== r 2) (== c 3))
(coalton/cell:write! found (Some (Tuple r c)))
(break :rows))))
(coalton/cell:read found)))
; => #.(TUPLE 2 3)