Contents

Functions are the primary unit of composition in Haze. A function may be a free function, a method declared in a trait, or a lambda expression. All three use the same call syntax, and a free function whose first parameter is the subject of the operation can be called with method syntax.

Declaring a Function#

A function declaration begins with fn, followed by the name, type parameters if any, the parameter list, and the return type. Parameters are written as a name followed by a type. A function with no return type annotation returns void.

fn greet(name str) {
    print($"hello, {name}")
}

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

The body is either an expression after => or a block. An expression body returns its expression. A block body may use return, or it may end with an expression whose type is assignable to the return type.

fn clamp(n i32, low i32, high i32) i32 {
    if n < low {
        return low
    }
    if n > high {
        return high
    }
    n
}

Modifiers#

pub makes a declaration visible to other modules. pure marks a function as suitable for compile-time evaluation and for use inside type invariants. The two modifiers may appear in either order before fn.

pub pure fn double(n i32) i32 => n * 2

pure is a promise that the compiler checks for direct calls. A type invariant may not call an impure function, only a pure function is folded at compile time, and a pure function may not call a known impure function or an impure builtin such as print. Indirect calls through a function value are not tracked, because the function type does not carry a purity annotation. Keep the promise even where the compiler cannot see the effect.

extern functions are declared separately because they have no Haze body and no contracts. They cannot be pure and cannot be used as first-class values. See Extern and C FFI.

Generic Functions#

A function declares type parameters in square brackets after its name. Type parameters may carry trait bounds. The compiler infers the arguments at each call site; there is no turbofish syntax for supplying them explicitly.

fn identity[T](value T) T => value

fn maximum[T Ord](a T, b T) T {
    if a.lt(b) {
        return b
    }
    return a
}

Bounds are separated from the parameter name by a space, as in T Ord. A parameterized bound uses brackets, as in T Convert[i64]. Multiple parameters may each carry bounds. The Generics and Traits chapters cover inference, instantiation, and bound resolution.

Contracts on Functions#

Contract clauses appear after the return type and before the body. A function may have any number of preconditions and postconditions, written inline or in a block. Named contracts use the same position.

fn divide(numerator i32, denominator i32) i32
    : pre denominator != 0
    : post r => r * denominator <= numerator
=> numerator / denominator

Contracts are the subject of the Design by Contract chapter. The important detail for function design is that a contract is part of the signature: callers may rely on a postcondition, and the compiler may use a precondition to reject an impossible call.

Method-Call Syntax#

A call of the form receiver.name(arguments) is rewritten to name(receiver, arguments). This works for free functions and for trait methods. The receiver is an ordinary first argument, not a hidden self reference.

fn scale(value i32, factor i32) i32 => value * factor

fn main() {
    print((3).scale(4))
    print([1, 2, 3].len)
}

A trait method call resolves through the receiver's type and its implementations. If no trait method matches, the compiler falls back to a free function with the same name. This is why collection helpers can be called with either style.

const names = people
    .filter(is_adult)
    .map(fn(person) => person.name)

Chained calls are parsed as successive postfix operations, so the pipeline above is equivalent to nested calls. Put each stage on its own line when the chain is long; the formatter preserves the layout.

Lambdas#

A lambda begins with fn followed by its parameter list. Parameter types may be omitted when an expected function type supplies them. The body is an expression after => or a block.

const double = fn(x i32) i32 => x * 2
const add_one = fn(x) => x + 1

A lambda used as an argument is checked against the corresponding parameter type. This is how the compiler infers the types of unannotated parameters.

fn apply[T, U](value T, transform fn(T) U) U => transform(value)

fn main() {
    print(apply(3, fn(x) => x * 2))
}

The function type syntax is fn(T, U) R. A function value may be stored in a const, passed to another function, or returned from a function. Generic functions and extern functions cannot be used as values because there is no single concrete signature to give them.

Closures and Capture#

A lambda captures the local bindings it mentions. Capture is by value: the closure receives a copy of each binding at the point where the lambda value is created. Rebinding the outer variable later does not change the captured copy. For a managed value, the copy is a reference, so mutations to the object's fields or elements remain visible.

fn make_adder(base i32) fn(i32) i32 => fn(x) => base + x

fn main() {
    const add_ten = make_adder(10)
    print(add_ten(5))
}

A closure is a managed value. Its captured environment is traced by the collector while the closure is reachable, and the compiler emits root information for captured managed values.

Recursion#

Haze functions may call themselves. Recursion is ordinary; there is no special syntax and no tail-call guarantee. Use a loop when the recursion depth is controlled by input size and the algorithm does not naturally decompose.

pure fn factorial(n i32) i32
    : pre n >= 0
    : pre n <= 12
    : post r => r >= 1
{
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

The preconditions bound the input so that the result fits in i32 and the recursion terminates. A recursive function without a decreasing argument and a base case is a defect, not a style choice.

Overloading and Names#

Haze does not support function overloading. A module may not declare two functions with the same name, and a function and a constant may not share a name in the same module. Use distinct names or a trait with multiple implementations when the same operation applies to different types.

fn render_i32(value i32) str => $"i32({value})"
fn render_str(value str) str => $"str({value})"

The Entry Point#

The entry module must define main. It takes no parameters. It may return void, in which case the process exits with status zero, or i32, in which case the value becomes the process exit status.

fn main() i32 {
    print("done")
    return 0
}

Process arguments are not passed to main. The standard environment module exposes them as a list of strings, and the runtime initializes that list before user code runs. The Modules chapter explains how to import it, and Memory and Garbage Collection explains why the list is a managed value.