Contents

Idiomatic Haze is not a list of syntax preferences. It is a way of deciding where each kind of guarantee belongs. The language gives you types, contracts, tests, and Result, and each one answers a different question. Code feels like Haze when those questions are answered in the right place and the implementation is written to make the answers obvious.

The Central Rule#

The most important distinction in the language is between a bug and an expected failure.

A bug is a caller passing an input outside the function's domain, or an implementation returning a value outside its guarantee. Bugs are handled by contracts and type invariants. A runtime contract violation panics, because the program has reached a state that its author said was impossible.

An expected failure is an operation that may legitimately fail: a file that is missing, input that is not valid, a network request that is refused. Expected failures are values. They are modelled with Result[T, E], handled with match or is, and propagated with ?.

Situation Idiomatic mechanism Failure behaviour
Input violates a documented domain Precondition Panic, because the caller has a bug
Implementation breaks a guarantee Postcondition Panic, because the implementation has a bug
A value would violate a type invariant Refinement plus checked construction Error returned by ?
An operation may fail for environmental reasons Result[T, E] Returned to the caller
A value may be absent Option[T] Returned to the caller
A concrete example needs checking Test with assert Test failure

Once this distinction is clear, most style questions answer themselves. Do not return Result for a programming error. Do not panic on a missing file. Do not use a sentinel such as -1 when Option is available. Do not restate a type invariant in every precondition.

The Hierarchy of Guarantees#

When more than one mechanism can express a property, choose the one closest to the value. The earlier a guarantee is established, the less code has to remember it.

Rank Mechanism Best for Example
1 Type The shape of the value and the set of valid states A sum type with one variant per state
2 Refinement or record invariant A predicate on a value that can be checked at construction Positive, a range with lo <= hi
3 Precondition A caller obligation that depends on the call context A non-empty list, a divisor, an index
4 Postcondition A relationship between inputs and outputs A sorted result, a preserved length
5 Loop invariant A property maintained by each iteration An accumulator's relationship to the index
6 Test A concrete behaviour that is not a general law An error message, a deferred cleanup order
7 Comment Context that is not a checkable claim Why an algorithm was chosen

The hierarchy is a preference, not a prohibition. A test is the right tool for verifying a specific error message even though it is lower than a postcondition. A comment is the right tool for explaining a trade-off that no executable predicate can capture. The mistake is using a comment for a property that a type or contract could enforce.

Contracts Before Bodies#

The contract is the interface. Write it before the body, and let the body be an implementation of the contract rather than a collection of statements that happen to work. A useful sequence is to state the domain, state the result guarantee, choose the data types that make the guarantee natural, and only then write the control flow.

contract Funded(account Account, amount i64) {
    pre amount > 0
    pre amount <= account.balance
}

fn withdraw(account Account, amount i64) Account
    : Funded(account, amount)
    : post r => r.id == account.id
    : post r => r.balance == account.balance - amount
=> Account { id = account.id, balance = account.balance - amount }

The contract says what the caller must provide and what the caller receives. The body is a single expression because the design has already made the operation total within its domain. If the body needed a conditional to handle a case the contract did not mention, the contract would be incomplete.

Types Before Contracts#

A property that can be represented in a type should not be repeated in every function signature. A positive integer is a Positive, not an i32 with a pre n > 0 clause on every function that uses it. A value that may be absent is an Option, not a sentinel. A value that has several mutually exclusive states is a sum type, not a record with flags that can contradict one another.

type Positive = i32 : invariant self > 0

type AccountState =
    | Open(balance Positive)
    | Frozen(balance Positive, reason str)
    | Closed(history List[Transfer])

The sum type makes an invalid combination unrepresentable. There is no is_open flag that can be true while the state is closed, and no balance that can be negative without failing construction. The contracts on functions that consume the state can then focus on the transition rather than on defensive checks.

Functional Composition in Imperative Code#

Haze is not a purely functional language, and idiomatic Haze does not pretend otherwise. Loops are clear for stateful processes, early return is clear for validation, and a local var is clear for an accumulator. At the same time, a transformation over a collection is usually clearer as a pipeline of small pure functions than as a loop with several mutable temporaries.

The style is to use the smallest tool that expresses the intent. A map says that every element is transformed. A filter says that a subset is selected. A fold says that a collection is reduced to one value. A for loop says that the process is sequential and may depend on the index or on state. Choose the form that matches the sentence you would use to describe the code.

fn active_names(accounts List[Account]) List[str] =>
    accounts
        .filter(is_open)
        .map(fn(account) => account.name)

The small helpers is_open and the field access are pure and obvious. The pipeline is the description of the result. When a transformation needs an index, a running total, or an early exit, a loop is the better description.

Immutable Data Flow#

Prefer producing a new value to mutating a shared one. This is not a moral rule about mutation; it is a way to keep contracts meaningful. A postcondition describes the relationship between the arguments and the result. If the function also mutates an argument, the postcondition sees the mutated value because Haze has no old expression, and the caller has to reason about two effects at once.

fn deposit(account Account, amount i64) Account
    : pre amount > 0
    : post r => r.balance == account.balance + amount
=> Account { id = account.id, balance = account.balance + amount }

The function returns a new record and leaves the input untouched. The postcondition is a statement about three values: the old account, the amount, and the new account. A caller can use the result without wondering whether the original changed.

Local mutation is fine. A loop that accumulates into a var is idiomatic when the loop is the clearest way to express the process. The rule is about boundaries: do not mutate a parameter or a shared value unless mutation is the documented purpose of the function.

Errors at the Boundary#

Parse and validate at the boundary, then work with precise types inside. A function that reads user input should return a Result with a structured error. Once the input has been parsed into a domain type, the rest of the program should not keep re-checking the same conditions. This is the "parse, don't validate" discipline, expressed with Haze's refinements and sum types.

type ParseError =
    | Empty
    | InvalidDigit(position i32, character u8)

fn parse_positive(text str) Result[Positive, ParseError] {
    if text.len == 0 {
        return Error(Empty)
    }
    const result = parse_i32(text)?
    return Success(Positive { result }?)
}

The caller handles ParseError once, at the boundary. Inside the domain, a Positive is trusted because it cannot exist otherwise. The error type carries enough context to produce a useful message without exposing the parser's internals.

The FFI Boundary Is a Last Resort#

C FFI is discouraged. Haze's contracts, purity, managed values, and error model do not cross the C boundary. An extern function has no contracts, cannot be pure, and deals in cstr, ptr, and C-layout records rather than in Haze strings, lists, and sum types. A program that reaches for FFI early gives up most of the language's advantages at exactly the point where correctness matters most.

Use FFI only for a capability that the language and standard library do not provide: a platform API, an existing C library, or an ABI that must be matched. Keep the extern surface as small as possible, convert to Haze types immediately, and expose a checked Haze function with contracts and Result errors. The FFI Boundary chapter gives the full policy.

The Review Questions#

Before calling a piece of Haze idiomatic, ask the following questions. A "no" is not automatically a defect, but it is a prompt to justify the choice.

Question Why it matters
Does every public function state its domain and its guarantee? The contract is the interface
Could a type or refinement carry a property that is currently a repeated check? Types remove whole classes of error
Are expected failures Result or Option rather than panics or sentinels? The caller can handle them
Does the function mutate a parameter or a shared value? Mutation complicates contracts and aliasing
Is the collection operation expressed at the right level? A pipeline describes a transformation; a loop describes a process
Is every non-obvious loop accompanied by an invariant? The invariant is the loop's contract
Is cleanup expressed with defer? Scope-based cleanup is reliable on every exit path
Is FFI isolated behind a checked wrapper? The boundary is where guarantees are lost
Are the boundary cases tested? Contracts state laws; tests exercise examples

Contracts First explains how to choose and place contracts. Modelling with Types explains how to move guarantees into the type system. Functional Imperative Style explains how to combine pipelines, loops, and local mutation. Errors as Values covers the failure model. The FFI Boundary explains when and how to leave Haze. The Review Checklist is a compact summary for daily use.