Skip to main content

Control Flow

Conditionals

if looks standard, with any number of else if branches and an optional final else:

if temp < 0 {
println("solid")
} else if temp < 100 {
println("liquid")
} else {
println("gas")
}

Conditionals are expressions, so they can be assigned or passed along:

state = if temp < 0 { "solid" } else { "liquid" }

The short-circuit operators && and || behave like logical "and" and "or", but only evaluate their right side if necessary. This makes them useful for guards:

nil?(m) && return

For matching a pattern in a condition, see if let and match.

while

while n > 0 {
n = n - 1
r = r * x
}

break exits the loop immediately; continue skips to the next iteration.

for

for iterates anything iterable – ranges, lists, strings, sequences:

for i = range(1, 10) {
println(i^2)
}

for ch = "hello" {
println(ch)
}

Note the = (not in). range(a, b) is inclusive on both ends.

Loops are statements: their value is nil. To build a list from a loop, append to a variable, or use map:

squares = []
for i = range(1, 5) {
append(&squares, i^2)
}

Under the hood, for x = xs { ... } calls iterate(xs) to get an iterator, then next(&itr) until it returns nil. Any type can become iterable by extending those two functions – see Collections & Iteration.

Labels

Loops can be labelled, letting break and continue target an outer loop:

@label outer
for i = range(0, 3) {
@label inner
for j = range(0, 3) {
if i == 1 && j == 1 { continue outer }
if i == 2 && j == 0 { break outer }
}
}

Unlabelled break and continue always target the nearest loop.

You can also label plain blocks. continue goes to the start of the block, and break to the end:

x = 3
@label blk
{
if x > 0 { break blk }
x = 0-x
}
note

A syntax gotcha: macro bodies want braces. if cond { return x } works; if cond return x on one line currently doesn't. The same goes for for and while bodies.