Nori language

7. Control Flow

if / else

if runs a block when a Bool condition holds; else and else if chain alternatives. The condition must be a Bool; there is no truthiness.

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

if as an expression

if/else can also be an expression that produces a value: each branch's final expression is its value, and the branches must share a type.

let grade = if score >= 90 { "A" } else if score >= 80 { "B" } else { "C" }
let sign  = if n < 0 { 0 - 1 } else { 1 }

An if used as an expression must have an else (every path must produce a value).

while

while repeats a block while a Bool condition holds.

var i = 0
while i < 10 {
    printl(to_str(i))
    i = i + 1
}

foreach

foreach iterates over a range or a collection.

Over a range lo..hi (from lo up to but not including hi):

var sum = 0
foreach i in 0..5 { sum = sum + i }    // 0+1+2+3+4 = 10

Over a collection (a Vec or a fill array), binding each element:

var xs: Vec<Int> = vec()
xs.push(3)  xs.push(4)  xs.push(5)
var total = 0
foreach x in xs { total = total + x }  // 12

When the compiler can prove the iterations are independent, foreach may be run in parallel automatically (see Concurrency); the source is unchanged and the result is identical.

break and continue

break exits the innermost loop; continue skips to its next iteration.

var i = 0
while true {
    i = i + 1
    if i % 2 == 0 { continue }   // skip evens
    if i > 9 { break }           // stop past 9
    printl(to_str(i))            // 1 3 5 7 9
}

Loop labels

Label a loop with name: on the same line as the loop, then break name / continue name to target it from an inner loop.

outer: foreach i in 0..3 {
    foreach j in 0..3 {
        if i + j == 3 { break outer }   // leaves both loops
    }
}

The label must be on the same line as break/continue. On the next line it would read as a bare break followed by a separate expression statement, leaving only the innermost loop; so the compiler refuses it:

error: the loop label must be on the same line as `break`
  fix:  write `break outer`; on the next line it reads as a separate statement and
        this would leave only the innermost loop

A ( or [ that continues an expression follows the same rule, for the same reason; see Statements and line breaks.

defer

defer S registers statement S to run when the enclosing block ends, by whatever path: falling off the end, an early return, a break/continue, or an exception-free unwinding like a region's exit. It is the way to say "when this scope ends, put that back", which auto-free covers for memory the language made and for nothing else (locks, saved interrupt flags, reference counts, raw blocks allocated by free-style FFI).

fn sys_readlinkat(dirfd: Int, upath: Int, ubuf: Int, size: Int) -> Int {
    if size <= 0 { return EINVAL() }
    let n = at_lookup(dirfd, upath, AT_SYMLINK_NOFOLLOW())
    if n < 0 { return n }
    if !inode_pin(n) { return ENOENT() }
    defer inode_unpin(n)                // on every path below: return, error, success
    if !is_lnk(n) { return EINVAL() }
    let t = link_target(n)
    ...
}

Rules and semantics:

match

match compares a value against patterns, running the first arm that matches. Arms are pattern => { body }. _ is the wildcard that matches anything.

Matching literal values (with an exhaustive wildcard):

fn classify(n: Int) -> Str {
    match n {
        0 => { return "zero" }
        1 => { return "one" }
        _ => { return "many" }
    }
}

Matching an enum and binding its payload:

enum Shape { Circle(Float)  Square(Float)  Nothing }

fn area(s: Shape) -> Float {
    match s {
        Shape::Circle(r) => { return 3.14 * r * r }
        Shape::Square(w) => { return w * w }
        Shape::Nothing   => { return 0.0 }
    }
}

match can also be used as an expression (each arm supplies a value of a common type). Patterns and exhaustiveness are covered fully in Enums and Pattern Matching.

if let and while let

When you care about a single variant, if let and while let are concise sugar for a two-arm match:

if let Shape::Circle(r) = s {
    printl("circle of radius " + to_str(r))
} else {
    printl("something else")
}

// drain a channel until it closes, say
while let Option::Some(v) = next() {
    handle(v)
}

Next: Functions and Closures.


← 6. Strings and Characters · Contents · 8. Functions and Closures →