navid/haze / 8ad27175ea7468984a380df035464efe6200afefbd75a9fe1bfd354d46029e85 / samples/baseline_2/main.hz

main.hz

← samples/baseline_2 · 1415 bytes · raw · download

// Functional chains and modules.

use seq
use seq {range, map, filter, fold, take, all}
use orders {Order, total, is_big}

fn add(a i32, b i32) i32 => a + b

fn main() {
    const squares = range(1, 11)
        .filter(fn(n) => n % 2 == 0)
        .map(fn(n) => n * n)
        .fold(0, add)

    print(squares)

    const orders = [
        Order{ id = 1, qty = 2,  price = 30 },
        Order{ id = 2, qty = 1,  price = 15 },
        Order{ id = 3, qty = 5,  price = 40 },
        Order{ id = 4, qty = 10, price = 2 },
    ]

    print(orders.map(total).fold(0, add))
    print(orders.filter(is_big).map(total).fold(0, add))

    const bulk_ids = orders
        .filter(fn(o) => o.qty > 1)
        .map(fn(o) => o.id)

    for id in bulk_ids {
        print(id)
    }

    const firsts = range(0, 100)
        .map(fn(n) => n * 3)
        .filter(fn(n) => n % 2 == 1)
        .take(4)

    for n in firsts {
        print(n)
    }

    print(seq::fold(seq::range(1, 6), 1, fn(acc, n) => acc * n))   // 120

    if orders.all(fn(o) => o.qty > 0) {
        print("all positive")                          // all positive
    } else {
        print("some empty")
    }

    // Each of these must be rejected:
    //
    // orders::BIG_ORDER          // error: `BIG_ORDER` is private to `orders`
    // range(5, 1)                // pre `lo <= hi` violated
    // orders.take(-1)            // pre `n >= 0` violated
}