diff --git a/spec/MaybeSpec.php b/spec/MaybeSpec.php index a79db2e..d16024f 100644 --- a/spec/MaybeSpec.php +++ b/spec/MaybeSpec.php @@ -29,6 +29,18 @@ expect($result)->toEqual(84); }); + it('uses the default value when extracting a Nothing', function () { + $maybe = Maybe::nothing(); + + expect($maybe->fromMaybe(42))->toBe(42); + }); + + it('return the inner value when extracting a Just', function () { + $maybe = Maybe::just(42); + + expect($maybe->fromMaybe(37))->toBe(42); + }); + it('maps a nothing to a nothing', function () { $maybe = Maybe::nothing(); diff --git a/src/Maybe.php b/src/Maybe.php index 5b86bdd..3b1165d 100644 --- a/src/Maybe.php +++ b/src/Maybe.php @@ -111,6 +111,22 @@ public function eval( return $ifNothing; } + /** + * @param A $a + * @return A + */ + public function fromMaybe($a) + { + return $this->eval( + $a, + /** + * @param A $a + * @return A + */ + fn($a) => $a + ); + } + /** * @template B * @param Functor $functor