return exits the nearest enclosing function immediately with zero, one, or multiple values.
Syntax
;; Return zero values (`Void`) from the enclosing function
(return)
;; Return the value(s) of `⟨expr⟩` from the enclosing function
(return ⟨expr⟩)
Semantics
returntransfers control out of the nearest enclosing function scope: a function-syntaxdefineor instance method definition (including nullary(define (f) ...)), a value-syntaxdefineor instance method definition that declares positional or keyword parameters, or an anonymousfn(unless thefnwas created with:transparent-to-return).(return)is equivalent to(return (values))and returnsVoid(zero values).(return ⟨expr⟩)evaluates⟨expr⟩and returns its result(s), which may be a single value,Void, or multiple values viavalues.- Every
returntargeting the same function, together with the final expression of that function’s body, must unify to the same return type. - Because
returnnever produces a value locally at the call site, the(return ...)expression itself unifies with any expected type in its surrounding expression. returnis invalid in a top-level value definition without parameters, in a standalone(coalton ...)expression outside any function, or inside the right-hand side of adobind(⟨pattern⟩ <- ⟨expr⟩).
Examples
(coalton-toplevel
;; Early return from a search loop
(declare find-first-negative ((Vector Integer) -> (Optional Integer)))
(define (find-first-negative v)
(let len = (coalton/vector:length v))
(for ((i 0 (+ i 1)))
:while (< i len)
(let x = (coalton/vector:index-unsafe i v))
(when (< x 0)
(return (Some x))))
None)
;; Early return of zero values (`Void`)
(declare guard-positive (Integer * (coalton/cell:Cell Integer) -> Void))
(define (guard-positive x cell)
(when (<= x 0)
(return))
(coalton/cell:write! cell x)
(values)))