v0.4.0
Generics · Lesson 13.5

Generic outcome

Source
Write reusable helpers over T? and Core's Result<T, E> as generic functions, so one helper serves every payload and error type.

Some questions get asked of outcomes again and again: "the value, or this fallback", "did it work?", "what went wrong, if anything?". For a struct you would answer them with methods. Optionals and sums are different: they are built into the language rather than declared by a package, so there is no package to own methods on them, and extend refuses them. The answer is a generic function whose parameter spells the form out — T?, or Core's Result<T, E> for an outcome that has been kept — and which therefore works for every payload and every error type at once.

Keeping an outcome

A call that throws is handled where it is made. When its outcome has to be kept — stored, passed on, asked about later — it goes into Core's Result<T, E>, an ordinary variant with the cases .Success(value) and .Failure(error):

func Divide(numerator: int32, denominator: int32) -> int32 throws DivisionByZero {
    if denominator == 0 {
        throw DivisionByZero { numerator: numerator };
    }
    return numerator / denominator;
}

// Keeps the outcome of one division instead of handling it here.
func KeepDivide(numerator: int32, denominator: int32) -> Result<int32, DivisionByZero> {
    return try .Success(Divide(numerator, denominator)) catch { e => .Failure(e) };
}

try … catch either wraps the quotient in .Success or catches the error and wraps it in .Failure. From here on, KeepDivide(12, 4) and KeepDivide(7, 0) are plain values of type Result<int32, DivisionByZero>, and nothing about them throws.

A parameter that spells out the form

ValueOr takes any Result and a fallback of its success type:

// The success, or `fallback` when there is none.
func ValueOr<T, E>(outcome: Result<T, E>, fallback: T) -> T {
    return match outcome {
        .Success(value) => value,
        .Failure(_) => fallback
    };
}

Nothing is written at the call. Given KeepDivide(12, 4), a Result<int32, DivisionByZero>, the compiler reads T = int32 and E = DivisionByZero straight out of the argument's type, the way it read T out of a Pair<T> in Generic type. The body is an ordinary variant match; the only new thing is that it is written once for every payload and every error type there will ever be.

Parameter writtenAcceptsHelpers in this lesson
Result<T, E>any kept outcomeSucceeded, Failed, ValueOr, SuccessOf, ErrorOf
T?any optionalBoth
T?[..]a slice of optionals of one typeCountPresent

Which case, without unwrapping

Succeeded and Failed answer which case an outcome holds. is only asks, so nothing is taken apart:

func Succeeded<T, E>(outcome: Result<T, E>) -> bool {
    return outcome is .Success(_);
}

func Failed<T, E>(outcome: Result<T, E>) -> bool {
    return outcome is .Failure(_);
}

Turning one form into another

Two small helpers move between the forms. SuccessOf keeps the success and forgets why there might not be one; ErrorOf keeps the other case:

func SuccessOf<T, E>(outcome: Result<T, E>) -> T? {
    return match outcome {
        .Success(value) => .Some(value),
        .Failure(_) => none
    };
}

func ErrorOf<T, E>(outcome: Result<T, E>) -> E? {
    return match outcome {
        .Success(_) => none,
        .Failure(error) => .Some(error)
    };
}
flowchart LR
    f(["`Result<T, E>`"]) -- "`SuccessOf`" --> s(["`T?`"])
    f -- "`ErrorOf`" --> e(["`E?`"])
    f -- "`ValueOr(fallback)`" --> t(["`T`"])
    f -- "`Succeeded` / `Failed`" --> b(["`bool`"])

ErrorOf(broken) is a DivisionByZero?, so Main can open it with a .Some(error) pattern and read the error's own field:

match ErrorOf(broken) {
    .Some(error) => PrintLine("ErrorOf      cannot divide {} by zero", error.numerator),
    none => PrintLine("ErrorOf      nothing went wrong")
}

Optionals too

Both combines two optionals of possibly different types. The postfix ? from Optional propagate does the work: if either is none, the function returns none on the spot.

func Both<T, U>(first: T?, second: U?) -> (T, U)? {
    return (first?, second?);
}

And a helper can take a whole slice of optionals. T?[..] is a slice of T?, so an int32?[4] array is passed straight to it, and is asks whether each one holds a T:

func CountPresent<T>(values: T?[..]) -> uint {
    var count: uint = 0;
    for value in values {
        if value is T {
            count++;
        }
    }
    return count;
}

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// Optionals and error sums are built into the language rather than declared by a package, so
// there is no package to own methods on them. `extend int32? { ... }` is rejected: "cannot extend
// native type 'int32?'". A question you keep asking of an optional is written instead as a
// generic function whose parameter spells the form out: `T?`.
//
// The same style serves an outcome kept as a value. A call that throws is handled where it is
// made, and when its outcome has to be kept, it goes into Core's `Result<T, E>`, an ordinary
// variant built with `try .Success(F()) catch { e => .Failure(e) }`. A helper over `Result<T, E>`
// works for every success type and every error type at once, and nothing needs to be written at
// the call: `T` and `E` are read straight out of the argument's type.
import Core::Result;
import Io::PrintLine;

struct DivisionByZero {
    numerator: int32;
}

func Divide(numerator: int32, denominator: int32) -> int32 throws DivisionByZero {
    if denominator == 0 {
        throw DivisionByZero { numerator: numerator };
    }
    return numerator / denominator;
}

// Keeps the outcome of one division instead of handling it here.
func KeepDivide(numerator: int32, denominator: int32) -> Result<int32, DivisionByZero> {
    return try .Success(Divide(numerator, denominator)) catch { e => .Failure(e) };
}

// Which case an outcome holds, without unwrapping it. `is` only asks, so nothing is taken apart.
func Succeeded<T, E>(outcome: Result<T, E>) -> bool {
    return outcome is .Success(_);
}

func Failed<T, E>(outcome: Result<T, E>) -> bool {
    return outcome is .Failure(_);
}

// The success, or `fallback` when there is none.
func ValueOr<T, E>(outcome: Result<T, E>, fallback: T) -> T {
    return match outcome {
        .Success(value) => value,
        .Failure(_) => fallback
    };
}

// Keeps the success and forgets why there might not be one.
func SuccessOf<T, E>(outcome: Result<T, E>) -> T? {
    return match outcome {
        .Success(value) => .Some(value),
        .Failure(_) => none
    };
}

// The other case: the error, if there is one.
func ErrorOf<T, E>(outcome: Result<T, E>) -> E? {
    return match outcome {
        .Success(_) => none,
        .Failure(error) => .Some(error)
    };
}

// Optionals too: both values when both are present, and nothing otherwise.
func Both<T, U>(first: T?, second: U?) -> (T, U)? {
    return (first?, second?);
}

// And a whole array of them: an `int32?[4]` is passed straight to the `T?[..]` slice.
func CountPresent<T>(values: T?[..]) -> uint {
    var count: uint = 0;
    for value in values {
        if value is T {
            count++;
        }
    }
    return count;
}

func Main() -> int {
    let even = KeepDivide(12, 4);
    let broken = KeepDivide(7, 0);
    PrintLine("ValueOr      {} {}", ValueOr(even, -1), ValueOr(broken, -1));
    PrintLine("Succeeded    {} {}", Succeeded(even), Succeeded(broken));
    PrintLine("Failed       {} {}", Failed(even), Failed(broken));
    PrintLine("SuccessOf    {}", SuccessOf(even) ?? 0);

    match ErrorOf(broken) {
        .Some(error) => PrintLine("ErrorOf      cannot divide {} by zero", error.numerator),
        none => PrintLine("ErrorOf      nothing went wrong")
    }

    let width: int32? = 80;
    let height: int32? = 24;
    let missing: char8[..]? = none;
    match Both(width, height) {
        .Some(size) => PrintLine("Both         {} x {}", size.0, size.1),
        none => PrintLine("Both         incomplete")
    }
    PrintLine("Both         complete: {}", Both(width, missing) is (int32, char8[..]));

    let readings: int32?[4] = [3, none, 5, none];
    PrintLine("CountPresent {} of {}", CountPresent(readings), readings.length);
    return 0;
}

Besides Io, its Rux.toml lists Core under [Dependencies].

Run it

cd Examples/Generics/GenericOutcome
rux run
ValueOr      3 -1
Succeeded    true false
Failed       false true
SuccessOf    3
ErrorOf      cannot divide 7 by zero
Both         80 x 24
Both         complete: false
CountPresent 2 of 4

Common mistakes

Try it yourself

  1. Write OrElse<T>(value: T?, fallback: T) -> T with ??, and call it with an int32? and a char8[..]?.
  2. Write IsPresent<T>(value: T?) -> bool, then rewrite CountPresent to use it.
  3. Write Either<T, E>(first: Result<T, E>, second: Result<T, E>) -> Result<T, E> that returns first if it succeeded and second otherwise.
  4. Keep the outcome of a throwing function from an earlier lesson in a Result and pass it to ValueOr. Did you have to change ValueOr?

Learn more