navid/haze / 67bab09d6ce4fc050f342167d2b41517cc673d31ca05891720d1159f7ab04485 / samples/baseline_2/main.hz

main.hz

← samples/baseline_2 · 1991 bytes · raw · download

// Functional chains and modules.
//
// Module rules used here:
//   - one file is one module, named after the file (no declaration line)
//   - items are private unless marked `pub`
//   - `import m`          gives qualified access only:       m::name
//   - `import m::{a, b}`  brings names into scope unqualified, so they work
//                         as plain calls and as dot-calls (UFCS): xs.a(...)
//   - `::` is for module paths; `.` stays for fields and UFCS

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)                                     // 220

    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))              // 295
    print(orders.filter(is_big).map(total).fold(0, add))   // 200

    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)                                       // 3, 9, 15, 21 (one per line)
    }

    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
}