Skip to content
Weaverv0.5.0

Control flow and patterns

if and match have a value, which a binding or a function can take:

import weaver.io.print
fn sign(n: Int): String = if n < 0 { "negative" } else if n == 0 { "zero" } else { "positive" }
fn describe(n: Int): String = match n {
0 => "none"
1 => "one"
2..=9 => "a few"
_ if n < 0 => "less than nothing"
_ => "many"
}
fn main() {
for n in [-4, 0, 1, 7, 42] { print("${n}: ${sign(n)}, ${describe(n)}") }
}
-4: negative, less than nothing
0: zero, none
1: positive, one
7: positive, a few
42: positive, many

A match arm is a pattern: a literal, a range, a variant with its fields, a tuple, _ for anything, and if adds a condition, a guard. The compiler checks that the arms cover every value.

There are three loops: for x in …, while condition and loop. Ranges replace C’s counting loop: a..b excludes b, a..=b includes it, and step sets the step.

import weaver.io.print
fn main() {
var evens: Int[] = []
for i in 0..10 step 2 { evens.push(i) }
print("${evens}")
var countdown: Int[] = []
for i in 3..=1 step -1 { countdown.push(i) }
print("${countdown}")
var n = 27
var steps = 0
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
steps += 1
}
print("27 reaches 1 in ${steps} steps")
val firstSquare = loop {
n += 1
if n * n > 50 { break n }
}
print("first square above 50: ${firstSquare}²")
}
[0, 2, 4, 6, 8]
[3, 2, 1]
27 reaches 1 in 111 steps
first square above 50: 8²

loop repeats until a break, which can give it a value. break and continue also take a label, continue 'rows, to leave an outer loop.

x is Pattern tests a value against a pattern, and binds its parts for the code that follows when it matches:

import weaver.io.print
enum Token = Number(value: Int) | Word(text: String) | End
fn main() {
val tokens = [Number(value: 3), Word(text: "apples"), End]
for t in tokens {
if t is Number(value) && value > 1 { print("several: ${value}") }
if t is Word(text) { print("word: ${text}") }
}
}
several: 3
word: apples

val Pattern = value else { … } binds for the rest of the block, the else leaving it when the value does not match. It keeps the normal path unindented:

import weaver.io.print
fn parsePair(line: String): (String, String)? {
val Some((key, value)) = line.splitOnce('=') else { return None }
return (key.trim(), value.trim())
}
fn main() {
for line in ["name = weaver", "broken"] {
match parsePair(line) {
Some((k, v)) => print("${k} is ${v}")
None => print("no '=' in ${line}")
}
}
}
name is weaver
no '=' in broken

while x is Pattern { … } loops as long as the pattern matches.