Language Tour
A tour of Haze values, types, contracts, generics, and modules.
Contents
Bindings and Functions#
var declares a binding that may be reassigned; const declares one that may not. Parameters are local bindings. A function returns with => or with return inside a block.
fn add(a i32, b i32) i32 => a + b
fn sum_to(n i32) i32 {
var total = 0
for i in 0..n {
total += i
}
return total
}
Integer literals default to i32 when they fit and i64 otherwise. The primitive types are i8 to i64, u8 to u64, f64, bool, str, rune, bytes, cstr, and ptr. See Primitive Types.
Records and Invariants#
type Account {
id i32
balance i64
}
type Positive = i64 : invariant self > 0
type Transfer : invariant src.id != dst.id {
src Account
dst Account
}
A refinement type such as Positive is a distinct type with the same representation as its base. A base value is not automatically a Positive; it must be built and checked. Arithmetic on a refinement produces the base type. See Refinement Types and Checked Construction.
Contracts#
Clauses may be written inline or packaged in a named contract.
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 }
Contracts are evaluated at compile time when the arguments are constant and become runtime checks otherwise. A failed runtime precondition or postcondition aborts; only checked construction returns an error value. See Contracts and Loop Invariants.
Sum Types#
type Shape =
| Circle(radius f64)
| Rect(width f64, height f64)
fn area(shape Shape) f64 => match shape {
Circle(radius) => 3.14159 * radius * radius
Rect(width, height) => width * height
}
A wildcard arm uses _. A refinement can be used as a pattern: n is Positive(p) tests the invariant and binds the value when it holds. See Pattern Matching and Option and Result.
Lists#
Lists use square brackets and have element type List[T]. An empty list needs a contextual element type from an annotation.
fn even_squares(xs List[i32]) List[i32] {
var out List[i32] = []
for x in xs {
if x % 2 == 0 {
out += [x * x]
}
}
return out
}
A free function whose first parameter is a list can be called with method syntax. map, filter, and fold are ordinary generic functions.
const values = [1, 2, 3, 4, 5]
.map(fn(x) => x * 2)
.filter(fn(x) => x > 4)
See Lists.
Generics#
Type parameters are declared in square brackets and inferred from the arguments. A type parameter may carry a trait bound.
fn identity[T](value T) T => value
fn largest[T Ord](a T, b T) T {
if a.lt(b) {
return b
}
return a
}
Generic records and sum types declare parameters after the name, as in Pair[A, B]. Instantiations use the same bracket syntax: Pair[i32, str] { first = 1, second = "one" }. See Generics.
Traits#
trait Eq {
pub fn eq(x, y Self) bool
pub fn neq(x, y Self) bool {
return !x.eq(y)
}
}
impl i32 of Eq {
pub fn eq(x, y Self) bool => x == y
}
Self is the implementing type. A bound such as T Ord makes Ord methods available on T. See Traits.
Modules#
Every file is a module. use imports another module, optionally naming symbols. Only pub declarations cross a module boundary.
use std/seq {map, filter}
use orders {Order, total}
fn main() {
const orders = [Order { id = 1, qty = 2, price = 30 }]
print(orders.map(total))
}
Module paths resolve relative to the importing file. core.hz is the conventional file name for a directory module. See Modules.
Defer#
defer registers a call or block to run when the enclosing scope exits. Defers run in last-in, first-out order, once per loop iteration, and during returns, breaks, continues, and ? propagation.
fn copy(input str, output str) Result[bool, str] {
defer print("copy finished")
if input == output {
return Error("same file")
}
return Success(true)
}
See Defer.
Memory#
Managed values are reclaimed automatically. The compiler tracks roots, so closures and local references remain valid across allocation points. str is an immutable string value; cstr is a raw C string used at the FFI boundary. See Memory and Garbage Collection and Extern and C FFI.