Option and Result
Option[T] and Result[T, E] are canonical standard-library datatypes used by
language and library protocols. They are ordinary typed values with constructors
and patterns, plus a few language forms that recognize their canonical
identities.
Option[T]
Section titled “Option[T]”An option is either Some(T) or None:
func value_or(option : Option[Int], fallback : Int) -> Int do switch option case Option::Some(value) then value case Option::None then fallback endendUse Option when absence is an expected state rather than an error requiring
diagnostic detail.
The fallback operator
Section titled “The fallback operator”option ?? fallback returns the contained value or evaluates the fallback for
None:
func display_name(name : Option[String]) -> String do name ?? "anonymous"endThe left side is evaluated once. The fallback is lazy: it is evaluated only
for None. ?? associates to the right, so chained fallbacks try each option
in order.
Optional chains
Section titled “Optional chains”?. applies a field access or method call only to Some and preserves absence:
type User = {name: String}
func optional_name(user : Option[User]) -> Option[String] do user?.nameendAn optional call uses ?( on an Option containing a function. Optional
chains skip later projections, calls, and arguments after a None. They map
results without implicitly flattening nested options.
Result[T, E]
Section titled “Result[T, E]”A result is either Ok(T) or Err(E):
datatype ParseIssue Invalidend
func show(result : Result[Int, ParseIssue]) -> String do switch result case Result::Ok(value) then value.to_string() case Result::Err(ParseIssue::Invalid) then "invalid" endendLibrary APIs may return Result directly. Functions declared with
throws E -> T also appear to callers as the canonical Result[T, E].
Propagation belongs to the language
Section titled “Propagation belongs to the language”Postfix ! is a language operation over the canonical Result and
AsyncResult identities. For a Result, it extracts Ok or returns Err
from the enclosing compatible throws function. It is not a general-purpose
operator that arbitrary two-constructor datatypes can opt into.
See Error handling for errortype, throws,
throw, and propagation, and Asynchronous code for
AsyncResult.
Equality and debugging
Section titled “Equality and debugging”The Prelude associates structural equality, ordering, hashing, and debugging
providers when the concrete contained types support those operations. An
Option[Int] can therefore be compared and traced structurally. These
providers are resolved through the same extension system as other generic
capabilities.
Next: Strings and characters.