Control Flow

Hale provides if/else branches, exhaustive match expressions, while loops, and for range/collection loops. Both if and match are expressions that can return…

Hale provides if/else branches, exhaustive match expressions, while loops, and for range/collection loops. Both if and match are expressions that can return values directly when all arms produce the same type.

fn classify(n: Int) -> String {
return match {
n < 0 -> "negative",
n == 0 -> "zero",
n < 10 -> "small",
else -> "large",
};
}
fn main() {
for i in 0..=3 {
let parity = if i % 2 == 0 { "even" } else { "odd" };
println(f"{i}: {parity} ({classify(i)})");
}
}

Control-Flow Summary

Section titled “Control-Flow Summary”
Construct Syntax Can Produce a Value? Key Rules
Conditional if cond { ... } else { ... } Yes (when else is present) Both arms must have the same type in expression position
Value match match expr { pat -> res, _ -> def } Yes Must be exhaustive; _ is the wildcard pattern; p1 | p2 -> res matches either
Condition match match { c1 -> r1, else -> def } Yes Evaluates boolean guards top-to-bottom; else is the catch-all
One-pattern test if let P = expr { ... } else { ... } Yes (when else is present) A two-arm match; P’s names are in scope in the first block only
Bind or leave let P = expr else { ... }; No P’s names are bound after the statement; the else block must leave (return, fail, break, continue)
Conditional loop while cond { ... } No (()) Use while true { ... } for unbounded loops; exit with break;
Iterator loop for x in 0..n { ... } No (()) a..b is half-open ([a, b)); a..=b is inclusive ([a, b]); a range’s bounds are Ints, and x is an Int
Block expression { stmt; expr } Yes (if final expression omits ;) Final expression without ; becomes the block’s value

if / else

Section titled “if / else”

if branches on a Bool condition and chains with else if and else:

if score >= 90 {
println("A");
} else if score >= 80 {
println("B");
} else {
println("C");
}

if as an Expression

Section titled “if as an Expression”

When an if has an else branch and both branches evaluate to the same type, it can be used as an expression:

let grade = if score >= 90 { "A" } else { "B" };
let band = if score >= 90 {
if score >= 97 { "A+" } else { "A" }
} else {
"B"
};

while and for Loops

Section titled “while and for Loops”

Use while to repeat a block while a condition holds, or while true for an explicit loop terminated by break;:

let mut i = 0;
while i < 5 {
println(i);
i = i + 1;
}
let mut n = 0;
while true {
n = n + 1;
if n >= 3 { break; }
}

Inside any loop, break; exits the innermost loop immediately, and continue; skips to the next iteration.

Use for to iterate over integer ranges or collections (covered in Collections):

for i in 0..5 {
println(i); // 0, 1, 2, 3, 4 (exclusive upper bound)
}
for i in 0..=5 {
println(i); // 0, 1, 2, 3, 4, 5 (inclusive upper bound)
}

To take a text apart, loop over one of the text sources, std::str::split(s, sep), std::str::lines(s) or std::str::words(s) (covered in Strings). A String itself is not something to loop over: for c in s is refused, since a part could be a byte, a character, a line or a word.

for line in std::str::lines("a=1\nb=2\n") {
println(line); // a=1, b=2
}

Pattern Matching (match)

Section titled “Pattern Matching (match)”

match compares a value against a list of patterns using -> arms and runs the first matching arm:

fn describe(n: Int) -> String {
return match n {
0 -> "zero",
1 -> "one",
_ -> "many",
};
}

Naming a variant with a leading dot

Section titled “Naming a variant with a leading dot”

The value being matched already says which enum an arm is about, so a pattern can name the variant alone with a leading dot: .Result(n) means Outcome::Result(n) when the value is an Outcome.

type Outcome = enum { Result(Int), Refused(String), Pending };
fn index_or(o: Outcome, fallback: Int) -> Int {
return match o {
.Result(n) -> n,
.Refused(_) | .Pending -> fallback,
};
}
fn refusal(o: Outcome) -> String {
if let .Refused(why) = o { why } else { "" }
}

Matching strings, and or-patterns

Section titled “Matching strings, and or-patterns”

A String matches against string literals, and an arm may list several patterns separated by |; the arm runs when any one of them matches. This is the way to dispatch on a word: one decision, the subject named once, and a _ arm that says what happens to everything else.

fn usage(verb: String) -> String {
return match verb {
"assign" | "unassign" -> verb + " <name> reviews <kind>:<node>",
"close" -> "close <name>",
_ -> "unknown verb",
};
}

Alternatives work for every pattern form: literals (1 | 2 | 3), enum variants with or without payloads, set members, tuples. When the alternatives bind names, every alternative binds the same names at the same types, so the arm’s body can use them whichever one matched:

type CtlError = enum { Invalid(String), NotFound(String), Conflict(String), NotReady(Int) };
fn problem(e: CtlError) -> String {
return match e {
CtlError::Invalid(p) | CtlError::NotFound(p) | CtlError::Conflict(p) -> p,
CtlError::NotReady(h) -> f"not ready after {h} checks",
};
}

A ladder of if verb == "assign" { … } else if verb == "close" { … } tests is the same decision spelled longer. hale check --warn-string-match (or hale verify --warn-string-match) points out three or more such tests in a row on one string and suggests the match.

Condition match (Scrutinee-less match)

Section titled “Condition match (Scrutinee-less match)”

Omit the value after match to test a sequence of boolean conditions top-to-bottom, using else as the catch-all arm:

let size = match {
n < 10 -> "small",
n < 100 -> "medium",
else -> "large",
};

Scrutinee-less match is shorthand for match true { _ if n < 10 -> ..., _ -> ... } and is ideal when routing or classifying across multiple predicates that return the same type:

return match {
std::http::is_route(ctx, "GET", "/users") -> self.list(),
std::http::is_route(ctx, "GET", "/users/:id") -> self.show(id),
else -> not_found(),
};

if let and let … else

Section titled “if let and let … else”

When one pattern is the whole question, if let tests it without writing the _ arm. It is the two-arm match match e { P -> { … }, _ -> { … } }, and like if it is an expression when it has an else:

type Side = enum { Buy, Sell, Other(String) };
fn label(side: Side) -> String {
if let Side::Other(raw) = side { "other: " + raw } else { "known" }
}
fn note(side: Side) {
if let Side::Other(raw) = side {
println("unrecognized side ", raw);
}
}

The pattern is any arm’s pattern, alternatives included (if let E::A(p) | E::B(p) = e { … }), and its names exist only inside the first block. Links chain with plain ones: if let … { } else if let … { } else if n > 0 { } else { }.

let … else is the other way round: bind the pattern’s names for the rest of the block, or leave. The else block runs when the pattern does not match, and it must leave, with return, fail, break or continue (or terminate / violate in a locus):

type Outcome = enum { Result(Int), Refused(String) };
fn doubled(o: Outcome) -> Int {
let Outcome::Result(index) = o else {
return -1;
};
return index * 2;
}

Block Values and Statement Rules

Section titled “Block Values and Statement Rules”

A { ... } block evaluates to its final expression when that expression omits the trailing semicolon ;:

let label = {
let base = compute();
base + 1 // no semicolon: block evaluates to `base + 1`
};

A block whose final item ends with ; has no value (()) and cannot be used where a value is expected.

A block whose last item is a match (no ; after its closing brace) takes the match’s value where the block is used as one — a let’s block, an arm of a match or if expression, the body of a function that returns a value (Functions) — so an arm can bind a local and then match on it. A trailing match whose every arm returns makes the block a diverging one: fine as a match arm, as an if arm beside one that yields the value, or as an or { … } substitute, but where the block alone must supply a value (a let’s block, a call argument, a condition, an operand of &&), hale check refuses it, as it refuses let x = { return 1; };:

let label = match kind {
Kind::A -> {
let m = n + 1;
match m { 1 -> "one", _ -> "many" }
},
Kind::B -> "b",
};

Conversely, a standalone statement terminated by ; must perform an action—such as a function or method call (whose return value, if any, is discarded), a locus instantiation, or an or clause on a fallible call. Writing a pure value expression as a statement (total + 1; or p.name;) fails compilation with this expression's value is unused.

Next: Records, Enums & Set Types.