Writing the filesystem examples made something rather obvious: a short sequence of operations could turn into a lot of nested code. Write a file, read it back, decode the bytes. Each operation could fail, so each successful branch contained another match.
The types told us what could go wrong. Following what the program actually did took more effort than it should.
That became the starting point for a programme of language ergonomics improvements. The changes are implemented on the development branch and planned for alpha.17. This is a preview of that release. The examples below need the development toolchain; they won't run unchanged in the released alpha.16 toolchain or the current website playground.
Start with the nesting
This is the shape of the filesystem example in alpha.16. The function returns either the note's text or an error message:
async write_and_read(file: Path): Result[Str,Str] {
match await files.write(file, "remember the milk".encode_utf8()) {
Error(problem) => Error(problem.render()),
Ok(written) => match await files.read(file, 1024) {
Error(problem) => Error(problem.render()),
Ok(data) => match utf8.decode(data) {
Error(decode_error) => Error("The note is not valid UTF-8."),
Ok(text) => Ok(text)
}
}
}
}The imports are stdlib/filesystem/async as files and stdlib/encoding/utf8 as utf8. Nothing particularly complicated is happening here, but the indentation keeps increasing because the next operation belongs inside the previous success case.
Here is the same function using the new syntax:
async write_and_read(file: Path): Result[Str,Str] {
await files.write(file, "remember the milk".encode_utf8()) or problem {
return Error(problem.render())
}
data <- await files.read(file, 1024) or problem {
return Error(problem.render())
}
text <- utf8.decode(data) or problem {
return Error("The note is not valid UTF-8.")
}
Ok(text)
}data <- ... takes the successful value out of a Result. If the operation fails, its error value is available as problem inside the or block. That name is chosen by the programmer. Here the block turns the filesystem's structured error into the string error that this function returns.
The write operation doesn't need a successful value, so it has no binding. We can still handle its error in exactly the same way.
When the enclosing function accepts the error type already, propagation needs no block:
data <- await files.read(file, 1024)An error returns immediately from the enclosing function. The success type of that function can be different from the read operation's success type; the propagated error must fit its declared error type. There is no implicit conversion from a filesystem error to a string.
For a successful value we don't need, the equivalent explicit propagation is:
await files.remove_file(file) or returnmatch is still useful when we want to inspect several alternatives. We now have a shorter way to express the common case of doing the next thing after an operation succeeds.
Cleanup stays visible
An early return skips whatever follows it. That matters when the file is temporary and we want to remove it after either a successful read or an error.
The temporary-note example saves the result of the work, attempts cleanup, then decides what to return:
async temporary_note(): Result[Str,Str] {
file <- await files.create_temp_file(paths.current()) or problem {
return Error(problem.render())
}
result = await write_and_read(file)
await files.remove_file(file) or cleanup {
result or original {
return Error("${original}\nCleanup also failed: ${cleanup.render()}")
}
return Error(cleanup.render())
}
result
}This adds the import stdlib/path as paths. The distinction between = and <- does useful work: result = ... keeps the whole Result, so a failure doesn't return before the removal attempt.
If cleanup succeeds, we return the saved result. If cleanup fails, we report that failure, preserving the original error as well when both operations failed. These are ordinary returned errors; this code doesn't promise cleanup after cancellation or process termination.
There is no finally block, exception mechanism or automatic cleanup hidden behind this syntax. The order of operations and the policy for competing errors are in the function.
The HTTP service becomes easier to follow
The status-service article used a clock reading and a shared counter to report uptime and requests handled. In alpha.16, startup and the handler both needed success branches around the work that followed a clock read.
The updated handler can deal with a clock failure near the operation, then carry on with the successful response:
server.get("/status", async (request, response): Result[Unit,Str] => {
total = await state.update(requests, (current) => current + 1)
now <- await time.now() or problem {
response.status(503)
response.send("Requests counted: ${total}; uptime unavailable: the clock could not be read.")
return Ok(())
}
response.send("Requests counted: ${total}; uptime: ${format.decimal(now.difference(started).as_seconds(), places: 3)} seconds")
Ok(())
})The failure path deliberately returns Ok(()): sending a 503 response is a handled outcome for this handler. The counter still increments before the clock read, just as it did in the original program.
The callback's parameter types come from server.get, and the counter callback's parameter type comes from state.update. They remain typed; we don't need to repeat types that the call already determines.
The response also shows expression interpolation. ${...} can contain a field access or function call, so we don't need temporary bindings purely to put a calculated value in a string. In this example, stdlib/format as format supplies format.decimal, which prints the exact duration to three decimal places. It returns a string and also works outside interpolation.
The full service also simplifies the default port to (arguments.first() ?? "8082").parse_nat(). That handles an absent argument; invalid input still needs a separate policy. The companion article, Ergonomic Panackelty, explores defaults, recovery, records, calls and the other everyday syntax changes.
The compiler checks the early exits in these examples, so a branch that returns or terminates the process doesn't need a dummy success value afterwards. The complete temporary-note example and updated status service include their imports and entry points. Website references and tutorials will follow with the alpha.17 release.