Namespace TH\Maybe\Result

ok

Return a Result\Ok Result containing $value.

$x = Result\ok(3);
self::assertTrue($x->isOk());
self::assertSame(3, $x->unwrap());

err

Return a Result\Err result.

Examples

$x = Result\err("nope");
self::assertTrue($x->isErr());
self::assertSame("nope", $x->unwrapErr());
$x->unwrap(); // @throws RuntimeException Unwrapping `Err`: s:4:"nope";

trap

Execute a callable and transform the result into an Result. It will be a Result\Ok containing the result or, if it threw an exception matching $exceptionClass, a Result\Err containing the exception.

Examples

Successful execution:

self::assertEq(Result\ok(3), Result\trap(fn () => 3));

Checked exception:

$x = Result\trap(fn () => new \DateTimeImmutable("2020-30-30 UTC"));
self::assertTrue($x->isErr());
$x->unwrap();
// @throws Exception Failed to parse time string (2020-30-30 UTC) at position 6 (0): Unexpected character

Unchecked exception:

Result\trap(fn () => 1/0);
// @throws DivisionByZeroError Division by zero

flatten

Converts from Result<Result<T, E>, E> to Result<T, E>.

Examples

$x = Result\ok(3);
self::assertSame(Result\flatten(Result\ok($x)), $x);

$x = Result\err("deity");
self::assertSame(Result\flatten($y = Result\ok($x)), $x);

self::assertEq(Result\flatten($x), Result\err("deity"));

transpose

Transposes a Result of an Option into an Option of a Result.

Ok(None) will be mapped to None. Ok(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

use TH\Maybe\Option;

self::assertSame(Result\transpose(Result\ok(Option\none())), Option\none());

$x = Result\ok(Option\some(4));
self::assertEq(Result\transpose($x), Option\some(Result\ok(4)));

$x = Result\err("meat");
self::assertEq(Result\transpose($x), Option\some($x));