From ae0dab4d2bfa5bcff50fc38e340bbc95048d0201 Mon Sep 17 00:00:00 2001 From: marcosh Date: Sat, 16 Oct 2021 16:58:26 +0200 Subject: [PATCH] add withDefault to Maybe --- spec/MaybeSpec.php | 12 ++++++++++++ src/Maybe.php | 16 ++++++++++++++++ 2 files changed, 28 insertions(+) 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