Option and Result
Absence, failure, matching, propagation, error types, and checked construction.
Contents
Option[T] and Result[T, E] are built-in sum types for the two most common forms of partiality. Option represents a value that may be absent. Result represents an operation that may fail with an error value. Neither has an unwrap; the caller must match, test, or propagate the outcome.
Option#
Option[T] has two variants. Some(value) contains a value of type T; None contains nothing. None is a bare expression and needs a contextual type when the element type cannot be inferred.
fn find_first_positive(values List[i32]) Option[i32] {
for value in values {
if value > 0 {
return Some(value)
}
}
return None
}
The return type supplies the element type in the function above. A local None needs an annotation.
const absent Option[i32] = None
const present = Some(42)
Some can be used as a value or tested with is. None is tested by name.
const value = find_first_positive([-3, 0, 5, 7])
if value is Some(n) {
print(n)
} else {
print("no positive value")
}
match value {
Some(n) => print(n)
None => print("missing")
}
Option is not a nullable pointer and it is not a sentinel. It is a distinct sum type. A function that returns Option[T] is telling the caller that absence is a normal outcome that must be handled.
Result#
Result[T, E] has two variants. Success(value) contains a value of type T; Error(reason) contains an error of type E. The error type is part of the signature and may be a primitive, a sum type, or a record.
type FsError =
| NotFound(path str)
| Denied(path str)
fn read_config(path str) Result[str, FsError] {
if path == "" {
return Error(NotFound(path))
}
return Success("configuration")
}
A Result is matched like any other sum. The success branch receives the value, and the error branch receives the reason.
match read_config("config.haze") {
Success(text) => print(text)
Error(NotFound(path)) => print($"missing {path}")
Error(Denied(path)) => print($"denied {path}")
}
The error type may be a string when the caller only needs a message, but a sum type is preferable when different failures require different handling. A dedicated error type makes the failure modes part of the function's contract.
Propagating with ?#
The postfix ? operator unwraps a Result on success and returns the error from the enclosing function on failure.
fn load_twice(path str) Result[str, FsError] {
const first = read_config(path)?
const second = read_config(path)?
return Success(first + second)
}
The enclosing function must itself return a Result with exactly the same error type. The operator does not convert between error types; map the error explicitly when the caller uses a different error domain.
fn load_message(path str) Result[str, str] => match read_config(path) {
Success(text) => Success(text)
Error(reason) => match reason {
NotFound(missing) => Error($"missing {missing}")
Denied(_) => Error("permission denied")
}
}
? is not defined for Option. An absent optional value must be handled with match or is, or converted to a Result with a meaningful error.
fn required(value Option[i32]) Result[i32, str] => match value {
Some(n) => Success(n)
None => Error("value is missing")
}
Checked Construction#
The same ? token has a second meaning after a record literal. T { ... }? constructs a value and checks its invariants at runtime, returning an Error instead of panicking when the value is invalid. This form is the bridge between Result and refinement types.
type Positive = i32 : invariant self > 0
fn make_positive(n i32) Result[Positive, str] => Success(Positive { n }?)
The enclosing function must return Result[_, str] when a runtime check is needed. The error is always a string of the form invariant failed for 'T'. If the compiler can verify the construction at compile time, the ? is redundant and produces a lint warning; if the construction is provably invalid, it is a compile error. The Checked Construction chapter covers the complete decision table.
Error Types#
The error type of a Result may be any type. The most common choices are a sum type for domain-specific failures, a str for simple messages, or a record that carries context.
| Error type | Use when |
|---|---|
str |
The caller only needs a message, or the function is a small internal helper |
| Sum type | Different failures need different recovery or different user-facing messages |
| Record | The error carries structured context such as a path, an identifier, or a cause |
Option |
Absence is expected and there is no meaningful reason to report |
A sum error type composes well with match because the caller can handle each failure explicitly. A string error is convenient but loses structure; convert it to a typed error at the boundary where the structure matters.
type ParseError =
| Empty
| InvalidDigit(position i32, character u8)
| Overflow
fn parse_i32(text str) Result[i32, ParseError] {
if text.len == 0 {
return Error(Empty)
}
var value = 0
for i in 0..text.len {
const digit = text[i]
if digit < 48 || digit > 57 {
return Error(InvalidDigit(i, digit))
}
value = value * 10 + cast[i32](digit - 48)
}
return Success(value)
}
No Unwrap#
Haze deliberately provides no unwrap, no expect, and no implicit panic for a failed Result or an empty Option. The only ways to obtain the payload are match and is, both of which require the caller to acknowledge the other case. The ? operator does not unwrap a failure; it propagates the failure to a caller that has declared it can fail.
This rule is the reason Haze programs do not have a hidden exception path. A function that can fail says so in its type, and a function that cannot fail has handled every failure internally.
Option or Result#
Use Option when absence is a normal, expected state and there is nothing useful to say about why the value is missing. Use Result when the caller needs a reason, when different failures require different recovery, or when the failure crosses a boundary such as parsing, input validation, or I/O.
A common pattern is to use Option inside a module and convert to Result at the public boundary, where the reason becomes part of the API. The conversion is explicit and cheap.
fn lookup(values List[i32], index i32) Option[i32] => values.get(index)
fn require_at(values List[i32], index i32) Result[i32, str] => match lookup(values, index) {
Some(value) => Success(value)
None => Error($"index {index} is out of range")
}
Composition#
Option and Result compose through matching. There is no monadic and_then in the core language, but a small helper function can express the same idea with an explicit type.
fn and_then[A, B, E](value Result[A, E], next fn(A) Result[B, E]) Result[B, E] =>
match value {
Success(a) => next(a)
Error(reason) => Error(reason)
}
The helper is ordinary Haze; there is no special syntax for chaining. This keeps the failure path visible and lets the programmer choose between a pipeline and an explicit sequence of ? bindings.
Testing#
Tests for functions returning Option or Result should assert both outcomes. assert is available inside test blocks only.
test "parse_i32 rejects empty input" {
assert parse_i32("") is Error(Empty)
}
test "parse_i32 accepts digits" {
const result = parse_i32("123")
if result is Success(value) {
assert value == 123
} else {
assert false
}
}
The is form is concise for verifying a variant. When the payload matters, bind it and assert the value separately.
test "invalid digit reports its position" {
const result = parse_i32("12x")
if result is Error(reason) {
match reason {
InvalidDigit(position, character) => {
assert position == 2
assert character == 120
}
_ => {
assert false
}
}
} else {
assert false
}
}