Less nesting, more Panackelty looks at the filesystem and HTTP examples that prompted the ergonomics work. This article covers the other part of that work: making ordinary code easier to write and read, including what happens when we want to recover from an error and carry on.
These changes are implemented on the development branch and planned for alpha.17. The examples need the development toolchain; they won't run unchanged in released alpha.16 or the current website playground.
Choose what recovery means
The first article used <- to obtain a successful value, with or problem blocks that returned early on failure. A recovery block can also supply a replacement value:
type Label = Str where text =>
text.len() >= 1 && text.len() <= 80 &&
text.is_non_blank() && text.has_no_control_characters()
pure label_or_default(raw: Str): Label {
label <- validate[Label](raw) or problem { Label("Untitled") }
label
}Valid input becomes label. If validation fails, the block supplies Untitled and execution continues after the binding. The replacement must satisfy the same Label type. We can't recover from a validation error by quietly substituting another invalid value.
That is a policy choice. A saved note might reasonably acquire a default title, while an explicitly supplied account label might need to be rejected. To return a readable error instead, the function could be:
pure checked_label(raw: Str): Result[Label,Str] {
label <- validate[Label](raw) or problem {
return Error(problem.render())
}
Ok(label)
}Omitting the or block propagates the original typed validation error, provided the enclosing function's result accepts that error type. Returning early and supplying a fallback are different outcomes, expressed where the decision is made.
Default an absent value
Absence has its own useful operation. The HTTP service's port selection changes from:
port = if arguments.len() == 0 { 8082 } else { arguments[0].parse_nat() }to:
port = (arguments.first() ?? "8082").parse_nat()first() returns an Option. ?? uses the value in Some, or evaluates the fallback when it receives None. The fallback is lazy, so a function call on the right would run only when needed.
We choose the text first, then parse it once. This doesn't make invalid text into port 8082, and it doesn't validate the port range. ?? handles absence; the validation and recovery above handle invalid values. There is no general ? operator connecting these decisions implicitly.
If we want different actions rather than a default value, a conditional pattern block gives us a local branch:
Some(argument) <- arguments.first() {
print("Using port argument ${argument}")
} or {
print("Using the default port")
}argument exists inside the matching block. With a Result, Ok(value) <- ... can similarly have an or problem branch that receives the error payload.
Say the fields once
Consider a small service configuration:
record Service { name: Str, port: Nat }
pure describe(service: Service): Str {
"${service.name} on port ${service.port}"
}An expected record type is enough to identify an inline literal:
name = "status"
service: Service = { name, port: 8082 }
print(describe({ name: "admin", port: 8083 })){ name, port: 8082 } means { name: name, port: 8082 }. The annotation supplies the expected type in the binding; the parameter supplies it in the call to describe. The compiler checks the fields against Service.
We can make a changed copy without repeating the fields we want to retain:
alternative = { ..service, port: 8083 }The original remains unchanged. Destructuring then lets us name the fields we need, in a binding or while iterating:
{ name: service_name, port } = service
print("${service_name}: ${port}")
for { name: listed_name, port: listed_port } in [service, alternative] {
print("${listed_name}: ${listed_port}")
}Here name: service_name gives the field a different local name. Destructuring also works in a typed parameter:
pure address({ port }: Service): Str {
"http://127.0.0.1:${port}"
}Make calls readable
Parameter defaults remove repetition at the call site, and names explain arguments that would otherwise be bare values:
pure endpoint(host: Str, port: Nat = 8082): Str {
"http://${host}:${port}"
}All three calls use the same function:
endpoint("127.0.0.1")
endpoint("127.0.0.1", port: 8083)
endpoint(port: 8083, host: "127.0.0.1")Supplied expressions run once in their written order. Omitted defaults are then evaluated in declaration order; defaults must be pure.
Stored callables can be invoked directly:
make_endpoint = @endpoint
make_endpoint("127.0.0.1", 8082)@endpoint refers to the function, not a name looked up in a string. A stored callable takes its full positional argument list: the declaration's labels and defaults don't travel with it.
Repeat while a pattern matches
A pattern loop is useful when each step may produce another item. Here a helper returns a line when the index is in range:
pure line_at(lines: [Str], index: Nat): Option[Str] {
if index < lines.len() { Some(lines[index]) } else { None() }
}
show_lines(lines: [Str]): Void {
mut index: Nat = 0
while Some(line) <- line_at(lines, index) {
index++
if line == "" { continue }
if line == "STOP" { break }
print(line)
} or {
print("Reached the end of the input.")
}
}The loop obtains one value per attempt. Empty lines advance to the next attempt; STOP exits immediately. The or block runs when the helper returns None, including if the input is empty. A break or a function return skips that block. It is an alternative for a failed match, not cleanup.
The same pattern works with Result: while Ok(item) <- ... can use or problem to handle the error that ends the loop. Ordinary loops also support break and continue.
Updates and text
The loop uses index++. Compound updates and postfix increments work on local mutable variables, with the usual type checks:
mut count: Nat = 0
count += 4
if count > 0 { count-- }
mut message: Str = "Requests counted: "
message += "${count}"The guard prevents Nat subtraction from underflowing. These are local updates; changing shared State still requires an explicit State operation. Postfix updates are statements, so an increment can't be tucked inside another calculation.
String interpolation accepts expressions, including fields, indexing, arithmetic and function calls. The describe function above uses two fields directly. We can also combine multiline text with a call:
summary = """
Service: ${service.name}
Address: ${address(service)}
Requests counted: ${count}
"""Shared leading indentation is removed from nonblank content lines, while additional indentation and intentional blank lines are preserved. Interpolated values keep their own whitespace. Expressions are evaluated once, from left to right, under the normal purity and async rules.
The HTTP example in the first article uses a call to format.decimal inside interpolation to choose three decimal places for uptime. That function also works wherever a string is needed. Together, these changes let the source say what should appear in the output without a collection of temporary variables just for formatting.