Functional Imperative Style
Pipelines, loops, local mutation, small pure functions, and the imperative shell around a pure core.
Contents
Idiomatic Haze is neither a functional language with imperative escape hatches nor an imperative language with a few callbacks. It is an imperative language whose expression forms make small transformations pleasant. The style that gets the most out of it is a pure core surrounded by an imperative shell.
The Pure Core#
A pure function depends only on its arguments and returns a value without effects. Pure functions are easy to test, easy to compose, and available to the compiler for contract folding. They are also 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)
Each function does one thing and names a domain concept. net_total reads as a sentence because the intermediate concepts have names. A contract or an invariant that calls these helpers can be evaluated at compile time when the arguments are constant.
The imperative shell is the part that reads input, writes output, manages resources, and decides what to do with a Result. It calls the pure core for every decision that can be expressed as a value.
Small Expressions, Named Steps#
An expression-bodied function is the right shape for a short computation. A block body is the right shape when the function needs local bindings, control flow, or a loop. Do not force a block when an expression is clearer, and do not force a chain when a loop is clearer.
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"
}
eligible and label are one-liners because the domain rule is one line. A longer rule should be split into named helpers rather than written as a deeply nested expression. The goal is readability, not a competition for the shortest body.
Pipelines for Transformations#
When the operation is a transformation of a collection, a pipeline describes it better than a loop with mutable temporaries. map transforms each element, filter selects a subset, and fold reduces the collection to a single 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))
The pipeline is ordinary function application. orders.filter(is_bulk) means filter(orders, is_bulk), and the method syntax is available because filter is a free function whose first parameter is the list. The lambda in map is inferred from the element type.
A pipeline is not a performance claim. It is a description of the shape of the computation. When the operation needs an index, an early exit, or a running state that is not a simple fold, a loop is the better description.
Local Mutation for Accumulation#
A var inside a function is idiomatic when it is the clearest way to accumulate a result. The restriction is at the boundary: do not mutate a parameter or a 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 two locals are implementation details. The function returns a new list and leaves the input unchanged. A caller can use the result without worrying about aliasing.
The same computation can be expressed as a fold, but the fold does not naturally produce the intermediate list without carrying a pair. The loop is clearer here because the process is sequential and stateful. A map would be wrong because each output depends on the previous input.
Loops as Processes#
A loop says that the computation is a process. Use a loop when the algorithm needs an index, a neighbouring element, an early exit, or a state that changes in a way 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
}
adjacent_differences needs the index and the next element. first_negative needs an early exit. Both are clearer as loops than as pipelines. The functional style is not a rule that forbids loops; it is a preference for the form that matches the intent.
Iteration and Invariants#
A loop whose correctness depends on an accumulator should carry an invariant. The invariant is the loop's contract, and it makes the relationship between the loop variable and the state explicit.
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
}
The invariant is simple and checkable. A more ambitious invariant, such as "the sum of the output is approximately 100", is a postcondition about the whole result rather than a statement about the loop header. Use the invariant for what the loop maintains; use a postcondition for what the function guarantees.
Higher-Order Functions#
A function that takes a function can express a family of operations without repeating the traversal. The standard sequence helpers are the common example, but the pattern is general.
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
}
apply_all and select are the shapes of map and filter. Writing them once makes the traversal correct once; callers supply the domain-specific part. The lambdas are small because the traversal is not repeated in every caller.
Defer for the Imperative Shell#
The shell often acquires a resource that must be released on every path. defer expresses the cleanup at the point of acquisition and guarantees it on normal exit, early return, and error propagation.
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 is one line, and it is impossible to forget on the error path. The alternative, a manual close before every return, duplicates the cleanup and creates a path where the resource leaks. The Defer chapter covers the ordering and restrictions.
Contracts and Composition#
A pure helper can be used in a contract. A contract can state the relationship between the helper's result and the function's output. This is how the pure core and the contract system reinforce each other.
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 is a named domain concept, the postcondition is a guarantee about the result, and the loop invariant is a local property that supports the postcondition. None of the three repeats the others.
Avoid Over-Abstraction#
Functional style can be taken too far. A chain of five higher-order functions that is read once is often worse than a loop with two named locals. A generic helper used once is usually worse than the concrete operation. A tiny function with a name that restates its body is noise.
The test is whether the abstraction names a concept that appears more than once or makes a complex operation easier to read. If it does neither, inline it. Haze rewards clarity, not a particular ratio of functions to lines.
A Complete Example#
The following program combines the ideas in this chapter. It has a pure core, a pipeline for a transformation, a loop for a stateful total, a checked parse at the boundary, and contracts on the public operations.
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))
}
The pure helpers state the pricing rules. The pipeline selects the bulk identifiers. The loop accumulates revenue with an invariant. The contracts on revenue state a property that holds for every list of orders. Each part is small enough to read on its own, and the composition is the program.
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 a 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 |
The next chapter, Errors as Values, explains how the imperative shell handles failure without losing the guarantees of the pure core.