Skip to content
ry

Result

A result is :Ok(value) or :Err(error), typed Result<T, E>. The alias is built in, so every annotation can use it.

@alias Result<T, E> {:Ok(T) | :Err(E)}
Function Summary
Result.is_ok Whether the result is :Ok.
Result.is_err Whether the result is :Err.
Result.with_default The :Ok value, or default for an :Err.
Result.map Applies f to an :Ok value and leaves an :Err alone.
Result.map_err Applies f to an :Err value and leaves an :Ok alone.
Result.map_both Applies on_ok to an :Ok value or on_err to an :Err value.
Result.map2 Combines two :Ok values with f, or returns the first :Err.
Result.and_then Chains a step that can fail: f gets the :Ok value and returns the next result.
Result.on_err Recovers from an :Err: f gets the error and returns the next result.
Result.is_ok <- function<T, E>(result: Result<T, E>) -> logical

Whether the result is :Ok.

Result.is_ok(:Ok(1L))
#> TRUE

Source

Result.is_err <- function<T, E>(result: Result<T, E>) -> logical

Whether the result is :Err.

Result.is_err(:Ok(1L))
#> FALSE

Source

Result.with_default <- function<T, E>(result: Result<T, E>, default: T) -> T

The :Ok value, or default for an :Err.

Result.with_default(:Err(:Missing), 0L)
#> 0L

Source

Result.map <- function<A, B, E>(result: Result<A, E>, f: fn(A) -> B) -> Result<B, E>

Applies f to an :Ok value and leaves an :Err alone.

Result.map(:Ok(2L), function(x) x * 10L)
#> :Ok(20L)

Source

Result.map_err <- function<T, A, B>(result: Result<T, A>, f: fn(A) -> B) -> Result<T, B>

Applies f to an :Err value and leaves an :Ok alone.

Result.map_err(:Err("disk full"), function(e) :IoError(e))
#> :Err(:IoError("disk full"))

Source

Result.map_both <- function<A, B, C, D>(result: Result<A, B>, on_ok: fn(A) -> C, on_err: fn(B) -> D) -> Result<C, D>

Applies on_ok to an :Ok value or on_err to an :Err value.

Result.map_both(:Err(404L), function(x) x, function(code) Str.concat("HTTP ", Num.to_str(code)))
#> :Err("HTTP 404")

Source

Result.map2 <- function<A, B, C, E, F>(first: Result<A, E>, second: Result<B, F>, f: fn(A, B) -> C) -> Result<C, E | F>

Combines two :Ok values with f, or returns the first :Err.

Result.map2(Str.to_integer("6"), Str.to_integer("7"), function(a, b) a * b)
#> :Ok(42L)

Source

Result.and_then <- function<A, B, E, F>(result: Result<A, E>, f: fn(A) -> Result<B, F>) -> Result<B, E | F>

Chains a step that can fail: f gets the :Ok value and returns the next result. The error type of the chain joins both, so a step can fail with a reason of its own.

Result.and_then(Str.to_integer("-3"), function(n) if (n > 0L) :Ok(n) else :Err(:NotPositive))
#> :Err(:NotPositive)

Source

Result.on_err <- function<T, A, B>(result: Result<T, A>, f: fn(A) -> Result<T, B>) -> Result<T, B>

Recovers from an :Err: f gets the error and returns the next result.

Result.on_err(Str.to_integer("x"), function(e) :Ok(0L))
#> :Ok(0L)

Source