Learn · 10

Option & Result

Handle optional values with T? and recoverable errors with T!E using ?, ??, and exhaustive match.

Ochre replaces null and runtime exceptions with two built-in types:

  • T? (Option) — a value that is either Some(v) or None.
  • T!E (Result) — an operation that either succeeds with Ok(v) or fails with Err(e).

Both types integrate with two ergonomic operators: ? (early-return propagation) and ?? (fallback coalescing).

Working with Option (T?)

Map lookups (m[key]), env(key), and recv(ch) return T?. Use ?? to provide a default or match to handle both cases explicitly:

fn find_positive(nums: List<Int>) -> Int? {
    for n in nums {
        if n > 0 {
            return Some(n)
        }
    }
    return None
}

fn main() {
    let first = find_positive([-3, -1, 7, 9]) ?? 0
    let fallback = find_positive([-3, -1]) ?? 0
    println("first={first}, fallback={fallback}")
}

Expected Output

first=7, fallback=0

Working with Result (T!E) and ? Propagation

When a function returns T!E, placing ? after any U!E expression unwraps Ok(v) or immediately returns Err(e) from the enclosing function:

fn safe_div(a: Float, b: Float) -> Float!Str {
    if b == 0.0 {
        return Err("division by zero")
    }
    return Ok(a / b)
}

fn compute_ratio(a: Float, b: Float) -> Float!Str {
    let q = safe_div(a, b)?
    return Ok(q * 100.0)
}

fn main() {
    let ok_val = compute_ratio(3.0, 4.0) ?? -1.0
    println("3/4 pct = {ok_val}")

    let msg = match compute_ratio(3.0, 0.0) {
        Ok(v) => "pct = {v}",
        Err(e) => "error: {e}",
    }
    println(msg)
}

Expected Output

3/4 pct = 75
error: division by zero

Dynamic JSON Parsing (json_parse)

json_parse(raw: Str) returns Any!Str because arbitrary JSON payloads have dynamic schemas at runtime. Unwrap it safely with ?? or match:

fn main() {
    let valid = '{"user": "Ada", "role": "admin"}'
    let parsed = json_parse(valid) ?? #{}
    let user = parsed["user"] ?? "unknown"
    println("user={user}")

    let bad = match json_parse('{broken') {
        Ok(_) => "ok",
        Err(e) => "parse failed: {e}",
    }
    println(bad)
}

Expected Output

user=Ada
parse failed: ...

Common Mistake: Using ? in a Non-Result Function

fn parse_port() -> Int!Str {
    return Ok(8080)
}

fn main() {
    let p = parse_port()?
}

Because main() returns Void (not T!Str), the compiler reports: '?' cannot propagate error 'Str' in this function and suggests using ?? or returning a compatible T!E type.

Exercise

Write validate_age(age: Int) -> Int!Str that returns Err("age must be non-negative") if age < 0, Err("age too large") if age > 150, and Ok(age) otherwise. Call it from a helper next_year(age: Int) -> Int!Str using ?.

Show Solution
fn validate_age(age: Int) -> Int!Str {
    if age < 0 {
        return Err("age must be non-negative")
    }
    if age > 150 {
        return Err("age too large")
    }
    return Ok(age)
}

fn next_year(age: Int) -> Int!Str {
    let valid = validate_age(age)?
    return Ok(valid + 1)
}

fn main() {
    println(next_year(28) ?? -1)
    let err = match next_year(-5) {
        Ok(v) => str(v),
        Err(e) => e,
    }
    println(err)
}