For the complete documentation index, see llms.txt. This page is also available as Markdown.

Nesting and conversion

Remove a level of nesting, or convert to a Result.

Flatten and Transpose are extension methods, in Waystone.Monads.Options.Extensions — add the using. OkOr and OkOrElse are on Option<T> itself and need nothing.

Flatten

Option<T> Flatten<T>(this Option<Option<T>> option)

Removes one level of nesting.

Option<Option<string>> some = Option.Some(Option.Some("Chetney"));
Option<string> result = some.Flatten();

On a None at either level: you get None.

This is the single-option Flatten. The one that drops the Nones out of a sequence is a different method — see Collections. No receiver is both, so the two never compete.

Transpose

Result<Option<T>, E> Transpose<T, E>(this Option<Result<T, E>> option)

Turns an option holding a result into a result holding an option.

Option<int> maybeNumber = Option.Try(() => RollD20());

Option<Result<int, string>> maybeResult = maybeNumber
    .Map(number => Divide(number, 2));

Result<Option<int>, string> result = maybeResult.Transpose();

Calling Transpose here declares that an Ok holding None is a valid outcome in your business rules.

On a None: you get Ok(None) — nothing failed, there was just nothing there.

Result<Option<T>, E> transposes the other way. See the Result page.

OkOr

Converts to a Result. A Some becomes an Ok, a None becomes an Err carrying the error you supplied.

Evaluated eagerly. If the error comes from a function call, use OkOrElse.

OkOrElse

The same, but the error is built only when the option is None.

Pass a factory only when there is something to defer. An error you already hold goes to OkOr — wrapping it in a lambda builds it just the same and allocates a delegate on top.

Going the other way

To convert a Result into an Option, see GetOk and GetErr.

Last updated

Was this helpful?