Contents

The style that gets the most out of Haze is a pure core surrounded by an imperative shell.

Pure Core#

Pure functions depend only on their arguments, are easy to test and compose, and can be folded by the compiler. They are the natural place for domain rules.

type Order {
    id    i32
    qty   i32
    price i64
}

pure fn total(order Order) i64 => cast[i64](order.qty) * order.price

pure fn is_bulk(order Order) bool => order.qty >= 10

pure fn discount(order Order) i64 => if is_bulk(order) {
    total(order) / 10
} else {
    0
}

pure fn net_total(order Order) i64 => total(order) - discount(order)

The imperative shell reads input, writes output, manages resources, and decides what to do with a Result.

Small Expressions, Named Steps#

Use an expression body for a short computation and a block body when the function needs local bindings, control flow, or a loop.

pure fn eligible(order Order) bool =>
    order.qty > 0 && order.price > 0 && is_bulk(order)

pure fn label(order Order) str => if is_bulk(order) {
    "bulk"
} else {
    "standard"
}

Split a longer rule into named helpers.

Pipelines#

map transforms each element, filter selects a subset, and fold reduces to one value.

fn bulk_order_ids(orders List[Order]) List[i32] =>
    orders
        .filter(is_bulk)
        .map(fn(order) => order.id)

fn subtotal(orders List[Order]) i64 =>
    orders.fold(0, fn(acc, order) => acc + total(order))

A pipeline is ordinary function application. orders.filter(is_bulk) means filter(orders, is_bulk).

Use a loop when the operation needs an index, an early exit, or running state that is not a simple fold.

Local Mutation#

A local var is idiomatic when it is the clearest way to accumulate a result. Do not mutate a parameter or shared object unless mutation is the purpose of the function.

fn running_total(values List[i32]) List[i32] {
    var out List[i32] = []
    var total = 0
    for value in values {
        total += value
        out += [total]
    }
    return out
}

The locals are implementation details. The input is unchanged.

Loops as Processes#

Use a loop when the algorithm needs an index, a neighbouring element, an early exit, or changing state that is not a simple reduction.

fn adjacent_differences(values List[i32]) List[i32] {
    var out List[i32] = []
    for i in 0..values.len - 1 {
        out += [values[i + 1] - values[i]]
    }
    return out
}

fn first_negative(values List[i32]) Option[i32] {
    for value in values {
        if value < 0 {
            return Some(value)
        }
    }
    return None
}

Iteration and Invariants#

A loop whose correctness depends on an accumulator should carry an invariant.

fn percentages(values List[i32], total i32) List[i32]
    : pre total > 0
    : pre values.len > 0
    : post r => r.len == values.len
{
    var out List[i32] = []
    for i in 0..values.len
        : invariant out.len == i
    {
        out += [values[i] * 100 / total]
    }
    return out
}

Use the invariant for what the loop maintains and a postcondition for what the function guarantees.

Higher-Order Functions#

A function that takes a function expresses a family of operations without repeating the traversal.

fn apply_all[T, U](values List[T], transform fn(T) U) List[U] {
    var out List[U] = []
    for value in values {
        out += [transform(value)]
    }
    return out
}

fn select[T](values List[T], keep fn(T) bool) List[T] {
    var out List[T] = []
    for value in values {
        if keep(value) {
            out += [value]
        }
    }
    return out
}

Defer#

Use defer for cleanup at the point of acquisition.

fn process(path str) Result[i32, str] {
    const file = open(path)?
    defer close(file)
    const first = read_line(file)?
    const second = read_line(file)?
    return Success(first.len + second.len)
}

The cleanup runs on normal exit, early return, and error propagation. See Defer.

Contracts and Composition#

pure fn order_total(order Order) i64 => cast[i64](order.qty) * order.price

fn checkout(orders List[Order]) i64
    : post r => r >= 0
{
    var total = 0
    for order in orders
        : invariant total >= 0
    {
        total += order_total(order)
    }
    return total
}

The helper names a domain concept, the postcondition guarantees a property of the result, and the loop invariant states a local property.

Over-Abstraction#

A chain of five higher-order functions read once is often worse than a loop with two named locals. A generic helper used once is usually worse than the concrete operation. Inline an abstraction that neither names a repeated concept nor makes a complex operation easier to read.

Complete Example#

type Order {
    id    i32
    qty   i32
    price i64
}

pure fn total(order Order) i64 => cast[i64](order.qty) * order.price
pure fn is_bulk(order Order) bool => order.qty >= 10
pure fn net(order Order) i64 => if is_bulk(order) {
    total(order) - total(order) / 10
} else {
    total(order)
}

fn bulk_ids(orders List[Order]) List[i32] =>
    orders
        .filter(is_bulk)
        .map(fn(order) => order.id)

fn revenue(orders List[Order]) i64
    : post r => r >= 0
{
    var sum = 0
    for order in orders
        : invariant sum >= 0
    {
        sum += net(order)
    }
    return sum
}

fn main() {
    const orders = [
        Order { id = 1, qty = 2, price = 30 },
        Order { id = 2, qty = 12, price = 10 },
    ]

    for id in bulk_ids(orders) {
        print(id)
    }
    print(revenue(orders))
}

Choosing the Form#

Intent Preferred form
Transform every element map
Select a subset filter
Reduce to one value fold
Need the index or a neighbour for over a range
Need an early exit for with return or break
Accumulate changing state for with a local var and an invariant
Acquire and release a resource defer
Describe a domain rule Pure named function
Express a relationship between input and output Postcondition
Express a stable property of a value Refinement or record invariant