module result

module lib/result.mu

import "result"

result provides helpers for the standardized result.Result shape so callers can reason about fallible helpers without checking type(...).

Imports

Functions

err#

fn err(message)

err wraps a message (or existing error) in a failure result.

Source lib/result.mu:15
err := fn(message) {
    error_value := message
    if error_value == nil {
        error_value = error("result.err called with no message")
    } else if type(error_value) != "ERROR" {
        error_value = error(error_value)
    }
    return shape.new("result.Result", {
        "ok": false,
        "error": error_value
    })
}

is#

fn is(value)

is reports whether value is a result.Result shape.

Source lib/result.mu:29
is := fn(value) {
    return shape.is(value, "result.Result")
}

match#

fn match(result, on_ok, on_err)

match dispatches based on result.ok and calls the provided handler.

Source lib/result.mu:34
match := fn(result, on_ok, on_err) {
    if result == nil {
        return nil
    }
    if result["ok"] {
        if on_ok == nil {
            return result["value"]
        }
        return on_ok(result["value"])
    }
    if on_err == nil {
        return result["error"]
    }
    return on_err(result["error"])
}

ok#

fn ok(value)

ok wraps the provided value in a success result.

Source lib/result.mu:7
ok := fn(value) {
    return shape.new("result.Result", {
        "ok": true,
        "value": value
    })
}

unwrap_or#

fn unwrap_or(result, fallback)

unwrap_or returns the success value or the provided fallback on failure.

Source lib/result.mu:51
unwrap_or := fn(result, fallback) {
    if result == nil {
        return fallback
    }
    if result["ok"] {
        return result["value"]
    }
    return fallback
}