Skip to content

Control flow and data

Everything on this page is in one script that sub check accepts and sub run prints the output of (shown at the end).

let mut total = 0
for (i in 0..5) {
if (i == 3) { continue }
total += i
}
let mut n = 10
while (n > 0) {
n -= 3
if (n < 4) { break }
}

0..5 stops before 5; 0..=5 includes it. continue and break work in for and while. += and -= change a let mut value.

let (a, b) = (1, 2)
let [first, second] = [10, 20]
let { name, port } = { name: "sub", port: 8080 }

Tuples, lists and records can be taken apart in let, for and match.

fn classify(n) {
match (n) {
0 => "zero",
x if x < 0 => "negative",
1..=9 => "small",
_ => "big"
}
}

A pattern can be a literal, a range, a name, a constructor or _. pattern if condition => is a guard. match must still cover every case.

let maybe = find([1, 2, 3, 4, 5], fn(x) { x > 3 })
if (let Some(v) = maybe) { print("found", v) }

The condition stays in parentheses; let goes inside them.

let xs = [1, 2, 3, 4, 5]
print(xs[1..3]) // [2, 3]
let m = #{ "a": 1, "b": 2 } // a map
let s = #[1, 2, 2, 3] // a set: #[1, 2, 3]
let who = None ?? "anon" // ?? gives a default
print("{who:>8}|", 0xff, 1_000, 2e3) // a format spec, hex, underscores, exponents
print(r"C:\raw\path") // a raw string

?. reads a field of an Option only when there is one. Strings can be raw (r"...") or triple-quoted.

flow.sub
let mut total = 0
for (i in 0..5) {
if (i == 3) { continue }
total += i
}
print(total)
let mut n = 10
while (n > 0) {
n -= 3
if (n < 4) { break }
}
print(n)
let (a, b) = (1, 2)
let [first, second] = [10, 20]
let { name, port } = { name: "sub", port: 8080 }
print(a + b, first + second, name, port)
fn classify(n) {
match (n) {
0 => "zero",
x if x < 0 => "negative",
1..=9 => "small",
_ => "big"
}
}
print(classify(0), classify(-4), classify(7), classify(100))
let xs = [1, 2, 3, 4, 5]
print(xs[1..3])
let m = #{ "a": 1, "b": 2 }
let s = #[1, 2, 2, 3]
print(m, s)
let maybe = find(xs, fn(x) { x > 3 })
if (let Some(v) = maybe) { print("found", v) }
let name2 = None ?? "anon"
print("{name2:>8}|", 0xff, 1_000, 2e3)
print(r"C:\raw\path")
7
1
3 30 sub 8080
zero negative small big
[2, 3]
{a: 1, b: 2} #[1, 2, 3]
found 4
anon| 255 1000 2000.0
C:\raw\path