navid/haze / 90400c3cb2eb4f37a299a5eb96dbf6c3ad2fda3fc79b7a824ce800f18386f55d / samples/baseline_2.7/option_result.hz

option_result.hz

← samples/baseline_2.7 · 1485 bytes · raw · download

// Option, Result, enums, is-patterns, ? propagation, and mutation.

type Color enum {
    Red
    Green
    Blue
}

type FsError = | NotFound(path str) | Denied(path str)

fn inner(ok bool) Result[i32, FsError] {
    if ok {
        return OK(10)
    }
    return Error(NotFound("/missing"))
}

fn outer(ok bool) Result[i32, FsError] {
    const value = inner(ok)?
    return OK(value + 1)
}

fn maybe(ok bool) Option[i32] {
    if ok {
        return Some(42)
    }
    return None
}

type Point {
    x i32
    y i32
}

fn main() {
    const some = maybe(true)
    if some is Some(value) {
        print(value)
    } else {
        print(-1)
    }

    const none = maybe(false)
    match none {
        Some(value) => print(value)
        None => print(0)
    }

    const color = Color.Green
    if color is Color.Green {
        print(99)
    }

    match color {
        Color.Red => print(1)
        Color.Green => print(2)
        Color.Blue => print(3)
    }

    const good = outer(true)
    if good is OK(value) {
        print(value)
    } else {
        print(-2)
    }

    const bad = outer(false)
    match bad {
        OK(value) => print(value)
        Error(err) => match err {
            NotFound(path) => print(path)
            Denied(path) => print(path)
        }
    }

    var point = Point{ x = 1, y = 2 }
    point.x = 5
    point.y = point.x + 1
    print(point.x)
    print(point.y)

    var values = [1, 2, 3]
    values[1] = 42
    print(values[1])
}