Learn · 06

Functions & Control Flow

Write typed functions, TypeScript-style closures, expression-oriented if/else, while loops, for..in ranges, and break/continue.

Functions are the primary unit of abstraction in Ochre. Parameter types are always explicit so function signatures serve as reliable contracts, while closures infer parameter types automatically when passed to higher-order functions.

Named Functions

Declare functions with fn. Omit -> ReturnType for Void functions. Use explicit return or a final tail expression:

fn clamp(val: Int, lo: Int, hi: Int) -> Int {
    if val < lo {
        return lo
    }
    if val > hi {
        return hi
    }
    return val
}

fn main() {
    println(clamp(-5, 0, 100))
    println(clamp(42, 0, 100))
    println(clamp(250, 0, 100))
}

Expected Output

0
42
100

if / else as an Expression

Because if/else is an expression, you can assign its result directly to a let binding without declaring a temporary var. Both branches must produce compatible types:

fn classify(temp_c: Int) -> Str {
    let label = if temp_c < 0 {
        "freezing"
    } else if temp_c < 22 {
        "cool"
    } else {
        "warm"
    }
    return label
}

fn main() {
    println(classify(-3))
    println(classify(18))
    println(classify(30))
}

Expected Output

freezing
cool
warm

Loops: for .. in and while

Iterate over exclusive integer ranges start..end or over List<T> elements with for, or loop conditionally with while. Both break and continue are supported:

fn main() {
    var sum = 0
    for i in 1..6 {
        sum += i
    }

    var n = 1
    while n < 100 {
        n *= 2
        if n == 32 {
            break
        }
    }
    println("sum={sum}, stopped_at={n}")
}

Expected Output

sum=15, stopped_at=32

TypeScript-Style Closures

Ochre supports concise arrow closures (params) => expr or (params) => { ... } that capture variables from their enclosing scope by value:

fn main() {
    let factor = 3
    let scale = (x: Int) -> Int => x * factor
    let nums = [1, 2, 3, 4]
    let scaled = map(nums, (n) => scale(n))
    println("scaled={scaled}")
}

Expected Output

scaled=[3, 6, 9, 12]

Common Mistake: Incompatible if/else Branches

fn main() {
    let x = if true { 10 } else { "ten" }
}

The compiler reports: 'if' branches have incompatible types: 'Int' vs 'Str'.

Practical Use Case: Guard Clauses

Early return guard clauses keep validation logic flat and readable instead of deeply nested if blocks.

Exercise

Write a recursive function factorial(n: Int) -> Int and print factorial(6) (expected: 720).

Show Solution
fn factorial(n: Int) -> Int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

fn main() {
    println(factorial(6))
}