when evaluates its body for side effects when a Boolean test is True, and returns Void (zero values).
Syntax
(when ⟨test-expr⟩
⟨body-element⟩*
⟨expr⟩)
Semantics
⟨test-expr⟩must have typeBoolean, and at least one body expression is required.- If
⟨test-expr⟩evaluates toTrue, the body is evaluated sequentially as an implicitprogn(supporting multiple expressions and shorthandletbindings). - If
⟨test-expr⟩evaluates toFalse, the body is not evaluated. - Any value(s) produced by the final
⟨expr⟩of the body are discarded; thewhenexpression always has typeVoid(zero values). - When the final body expression already has type
Void, it remains in tail position if thewhenexpression is in tail position (including forrectail calls).
Examples
(coalton-toplevel
;; Guard an early return inside a function
(declare first-positive ((List Integer) -> (Optional Integer)))
(define (first-positive xs)
(for ((rem xs (match rem ((Cons _ tl) tl) ((Nil) Nil))))
:while (not (coalton/list:null? rem))
(match rem
((Cons x _)
(when (> x 0)
(return (Some x))))
((Nil) (values))))
None))
Other notes
- Because
whenreturnsVoid(zero values) rather thanUnit, a function declared(Foo -> Unit)that ends with awhenform should followwhenwithUnit(or be declared(Foo -> Void)). - Use
unlessfor the negated test(when (not test) ...).