Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Control flow

All control forms are expressions.

if, cond, and when

(if (> score 0) "positive" "not positive")

(cond
  (< score 0) "negative"
  (= score 0) "zero"
  "positive")

(when ready?
  (println! "go"))

(unless ready?
  (println! "wait"))

cond tests each condition in order. Its last unpaired expression is the default branch. when, when-not, and unless are bundled macros. when and when-not are for effects: their implicit false branch is nil, so use if or cond when both branches must produce a useful value.

while and loop

while runs while its condition is true. The counter-style loop macro introduces and updates its named counter for you:

(mut i 0)
(while (< i 3)
  (println! (Integer->String i))
  (++ i))

(loop i (< i 3)
  (println! (Integer->String i)))

println! has type [Char] -> (): convert an Int with Integer->String, or build text with functions such as join.

There are library macros for common forms:

(loop/for i 1 (<= i 10) (++ i) (println! (Integer->String i)))
(loop/in value [10 20 30] (println! (Integer->String value)))
(loop/in/i index value [10 20]
  (println! (join ":" [(Integer->String index) (Integer->String value)])))
(times 3 (println! "tick"))

The correctness analyser recognizes many counter loops and can show the initial value, condition, update, and exit bound in que explain. It is conservative: “unknown” means it did not establish a proof, not that the loop is definitely infinite.

block and do

Use block when a control-flow branch needs its own bindings. Use do only when you need explicit sequencing without a new scope.