diff --git a/CHANGELOG.md b/CHANGELOG.md index 66e297c..6f364df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added - `Innmind\Immutable\Sequence::sink()` +- `Innmind\Immutable\Attempt` ### Fixed diff --git a/docs/structures/attempt.md b/docs/structures/attempt.md new file mode 100644 index 0000000..32180ed --- /dev/null +++ b/docs/structures/attempt.md @@ -0,0 +1,197 @@ +# `Attempt` + +This structures is similar to [`Either`](either.md) but where the left value is necessarily an instance of `\Throwable`. + +Its main use is as a return type of any function that would normally throw an exception. Instead of throwing and let the exception bubble up the call stack, it's caught in the structure and forces you to deal with this exception at some point. + +Unlike an `Either` the error type can't be more precise than `\Throwable`. + +`Attempt` is intended to be used as a return type where the call may fail but you can't know in advance all the possible failing scenarii. This is the case for interfaces where the kind of error will depend on the implementation details. + +If you already know all the possible failing scenarii you should use an `Either` instead. + +??? note + In other languages this monad is called `Try`. But this is a reserved keyword in PHP, hence the name `Attempt`. + +## `::error()` + +This builds an `Attempt` that failed with the given exception: + +```php +$attempt = Attempt::error(new \Exception); +``` + +!!! note "" + You will rarely use this method directly. + +## `::result()` + +This builds an `Attempt` that succeeded with the given value: + +```php +$attempt = Attempt::result($anyValue); +``` + +!!! note "" + You will rarely use this method directly. + +## `::of()` + +This builds an `Attempt` that will immediately call the callable and catch any exception: + +```php +$attempt = Attempt::of(static function() { + if (/* some condition */) { + throw new \Exception; + } + + return $anyValue; +}); +``` + +This is the equivalent of: + +```php +$doStuff = static function() { + if (/* some condition */) { + return Attempt::error(new \Exception); + } + + return Attempt::result($anyValue); +}; +$attempt = $doStuff(); +``` + +!!! success "" + This is very useful to wrap any third party code to a monadic style. + +## `::defer()` + +This builds an `Attempt` where the callable passed will be called only when [`->memoize()`](#-memoize) or [`->match()`](#-match) is called. + +```php +$attempt = Attempt::defer(static fn() => Attempt::of(doStuff(...))); +// doStuff has not been called yet +$attempt->memoize(); +// doStuff has been called +``` + +The main use case is for IO operations. + +## `->map()` + +This will apply the map transformation on the result if no previous error occured. + +=== "Result" + ```php + $attempt = Attempt::of(static fn() => 1/2) + ->map(static fn(int $i) => $i*2); + ``` + + Here `#!php $attempt` contains `1`; + +=== "Error" + ```php + $attempt = Attempt::of(static fn() => 1/0) + ->map(static fn(int $i) => $i*2); + ``` + + Here `#!php $attempt` contains a `DivisionByZeroError` and the callable passed to `map` has not been called. + +## `->flatMap()` + +This is similar to `#!php ->map()` except the callable passed to it must return an `Attempt` indicating that it may fail. + +```php +$attempt = Attempt::result(2 - $reduction) + ->flatMap(static fn(int $divisor) => Attempt::of( + static fn() => 42 / $divisor, + )); +``` + +If `#!php $reduction` is `#!php 2` then `#!php $attempt` will contain a `DivisionByZeroError` otherwise for any other value it will contain a fraction of `#!php 42`. + +## `->match()` + +This extracts the result value but also forces you to deal with any potential error. + +```php +$result = Attempt::of(static fn() => 2 / $reduction)->match( + static fn($fraction) => $fraction, + static fn(\Throwable $e) => $e, +); +``` + +If `#!php $reduction` is `#!php 0` then `#!php $result` will be an instance of `DivisionByZeroError`, otherwise it will be a fraction of `#!php 2`. + +## `->recover()` + +This will allow you to recover in case of a previous error. + +```php +$attempt = Attempt::of(static fn() => 1/0) + ->recover(static fn(\Throwable $e) => Attempt::result(42)); +``` + +Here `#!php $attempt` is `#!php 42` because the first `Attempt` raised a `DivisionByZeroError`. + +## `->maybe()` + +This converts an `Attempt` to a `Maybe`. + +=== "Result" + ```php + Attempt::result($value)->maybe(); + // is the same as + Maybe::just($value); + ``` + +=== "Error" + ```php + Attempt::error(new \Exception)->maybe() + // is the same as + Maybe::nothing(); + ``` + +## `->either()` + +This converts an `Attempt` to a `Either`. + +=== "Result" + ```php + Attempt::result($value)->either(); + // is the same as + Either::right($value); + ``` + +=== "Error" + ```php + Attempt::error(new \Exception)->either() + // is the same as + Either::left(new \Exception); + ``` + +## `->memoize()` + +This method force to load the contained value into memory. This is only useful for a deferred `Attempt`, this will do nothing for other attempts as the value is already known. + +```php +Attempt::defer(static fn() => Attempt::result(\rand())) + ->map(static fn($i) => $i * 2) // value still not loaded here + ->memoize() // call the rand function and then apply the map and store it in memory + ->match( + static fn($i) => doStuff($i), + static fn() => null, + ); +``` + +## `->unwrap()` + +This will return the result or throw any previous error. + +```php +$result = Attempt::of(static fn() => 1 / $divisor) + ->unwrap(); +``` + +Here `#!php $result` is necessarily a fraction of `#!php 1` but this code may raise the `DivisionByZeroError` exception. diff --git a/docs/structures/index.md b/docs/structures/index.md index 6cbe744..848ed5a 100644 --- a/docs/structures/index.md +++ b/docs/structures/index.md @@ -9,6 +9,7 @@ This library provides the following structures: - [`RegExp`](regexp.md) - [`Maybe`](maybe.md) - [`Either`](either.md) +- [`Attempt`](attempt.md) - [`Validation`](validation.md) - [`Identity`](identity.md) - [`State`](state.md) diff --git a/mkdocs.yml b/mkdocs.yml index 10793b5..4353935 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -13,6 +13,7 @@ nav: - RegExp: structures/regexp.md - Maybe: structures/maybe.md - Either: structures/either.md + - Attempt: structures/attempt.md - Validation: structures/validation.md - Identity: structures/identity.md - State: structures/state.md diff --git a/proofs/attempt.php b/proofs/attempt.php new file mode 100644 index 0000000..6185e27 --- /dev/null +++ b/proofs/attempt.php @@ -0,0 +1,362 @@ + throw $e); + + $assert->same( + $e, + $attempt->match( + static fn() => null, + static fn($e) => $e, + ), + ); + }, + ); + + yield proof( + 'Attempt::map()', + given( + Set\Type::any(), + Set\Type::any(), + $exceptions, + ), + static function($assert, $start, $end, $e) { + $attempt = Attempt::result($start) + ->map(static function($value) use ($assert, $start, $end) { + $assert->same($start, $value); + + return $end; + }); + + $assert->same( + $end, + $attempt->match( + static fn($value) => $value, + static fn() => null, + ), + ); + + $attempt = Attempt::error($e) + ->map(static fn() => $end); + + $assert->same( + $e, + $attempt->match( + static fn() => null, + static fn($value) => $value, + ), + ); + }, + ); + + yield proof( + 'Attempt::flatMap()', + given( + Set\Type::any(), + Set\Type::any(), + $exceptions, + ), + static function($assert, $start, $end, $e) { + $attempt = Attempt::result($start) + ->flatMap(static function($value) use ($assert, $start, $end) { + $assert->same($start, $value); + + return Attempt::result($end); + }); + + $assert->same( + $end, + $attempt->match( + static fn($value) => $value, + static fn() => null, + ), + ); + + $attempt = Attempt::result($start) + ->flatMap(static function($value) use ($assert, $start, $e) { + $assert->same($start, $value); + + return Attempt::error($e); + }); + + $assert->same( + $e, + $attempt->match( + static fn() => null, + static fn($value) => $value, + ), + ); + + $attempt = Attempt::error($e) + ->flatMap(static fn() => Attempt::result($end)); + + $assert->same( + $e, + $attempt->match( + static fn() => null, + static fn($value) => $value, + ), + ); + }, + ); + + yield proof( + 'Attempt::recover()', + given( + $exceptions, + $exceptions, + Set\Type::any(), + ), + static function($assert, $start, $end, $value) { + $attempt = Attempt::error($start) + ->recover(static function($e) use ($assert, $start, $end) { + $assert->same($start, $e); + + return Attempt::error($end); + }); + + $assert->same( + $end, + $attempt->match( + static fn() => null, + static fn($value) => $value, + ), + ); + + $attempt = Attempt::error($start) + ->recover(static function($e) use ($assert, $start, $value) { + $assert->same($start, $e); + + return Attempt::result($value); + }); + + $assert->same( + $value, + $attempt->match( + static fn($value) => $value, + static fn() => null, + ), + ); + + $attempt = Attempt::result($value) + ->recover(static fn() => Attempt::error($end)); + + $assert->same( + $value, + $attempt->match( + static fn($value) => $value, + static fn() => null, + ), + ); + }, + ); + + yield proof( + 'Attempt::maybe()', + given( + Set\Type::any(), + $exceptions, + ), + static function($assert, $result, $e) { + $assert->same( + $result, + Attempt::result($result) + ->maybe() + ->match( + static fn($value) => $value, + static fn() => null, + ), + ); + $assert->true( + Attempt::error($e) + ->maybe() + ->match( + static fn() => false, + static fn() => true, + ), + ); + }, + ); + + yield proof( + 'Attempt::either()', + given( + Set\Type::any(), + $exceptions, + ), + static function($assert, $result, $e) { + $assert->same( + $result, + Attempt::result($result) + ->either() + ->match( + static fn($value) => $value, + static fn() => null, + ), + ); + $assert->same( + $e, + Attempt::error($e) + ->either() + ->match( + static fn() => null, + static fn($value) => $value, + ), + ); + }, + ); + + yield proof( + 'Attempt::memoize()', + given( + Set\Type::any(), + $exceptions, + ), + static function($assert, $result, $e) { + $assert->same( + $result, + Attempt::result($result) + ->memoize() + ->match( + static fn($value) => $value, + static fn() => null, + ), + ); + $assert->same( + $e, + Attempt::error($e) + ->memoize() + ->match( + static fn() => null, + static fn($value) => $value, + ), + ); + + $called = 0; + $attempt = Attempt::defer(static function() use ($result, &$called) { + ++$called; + + return Attempt::result($result); + }); + + $assert->same(0, $called); + $assert->same( + $result, + $attempt + ->memoize() + ->match( + static fn($value) => $value, + static fn() => null, + ), + ); + $attempt->memoize(); + $assert->same(1, $called); + + $called = 0; + $attempt = Attempt::defer(static function() use ($e, &$called) { + ++$called; + + return Attempt::error($e); + }); + + $assert->same(0, $called); + $assert->same( + $e, + $attempt + ->memoize() + ->match( + static fn() => null, + static fn($value) => $value, + ), + ); + $attempt->memoize(); + $assert->same(1, $called); + }, + ); + + yield proof( + 'Attempt::defer()', + given( + Set\Type::any(), + Set\Type::any(), + $exceptions, + $exceptions, + ), + static function($assert, $result1, $result2, $e1, $e2) { + $loaded = false; + $attempt = Attempt::defer(static function() use ($result1, &$loaded) { + $loaded = true; + + return Attempt::result($result1); + }) + ->map(static fn() => $result2) + ->flatMap(static fn() => Attempt::error($e1)) + ->recover(static fn() => Attempt::error($e2)); + + $assert->false($loaded); + $attempt->maybe(); + $assert->false($loaded); + $attempt->either(); + $assert->false($loaded); + + $attempt->memoize(); + $assert->true($loaded); + + $assert->same( + $e2, + $attempt->match( + static fn() => null, + static fn($value) => $value, + ), + ); + $assert->false( + $attempt->maybe()->match( + static fn() => true, + static fn() => false, + ), + ); + $assert->same( + $e2, + $attempt->either()->match( + static fn() => null, + static fn($value) => $value, + ), + ); + }, + ); + + yield proof( + 'Attempt::unwrap()', + given( + Set\Type::any(), + $exceptions, + ), + static function($assert, $result, $e) { + $assert->same( + $result, + Attempt::result($result)->unwrap(), + ); + + $assert->throws( + static fn() => Attempt::error($e)->unwrap(), + $e::class, + ); + }, + ); +}; diff --git a/src/Attempt.php b/src/Attempt.php new file mode 100644 index 0000000..0d25da8 --- /dev/null +++ b/src/Attempt.php @@ -0,0 +1,177 @@ + */ + private Implementation $implementation; + + /** + * @param Implementation $implementation + */ + private function __construct(Implementation $implementation) + { + $this->implementation = $implementation; + } + + /** + * @template U + * @psalm-pure + * + * @return self + */ + public static function error(\Throwable $error): self + { + return new self(new Error($error)); + } + + /** + * @template U + * @psalm-pure + * + * @param U $value + * + * @return self + */ + public static function result(mixed $value): self + { + return new self(new Result($value)); + } + + /** + * This method is to be used for IO operations + * + * @template U + * @psalm-pure + * + * @param callable(): self $deferred + * + * @return self + */ + public static function defer(callable $deferred): self + { + return new self(new Defer($deferred)); + } + + /** + * @template U + * @psalm-pure + * + * @param callable(): U $try + * + * @return self + */ + public static function of(callable $try): self + { + try { + /** @psalm-suppress ImpureFunctionCall */ + return self::result($try()); + } catch (\Throwable $e) { + return self::error($e); + } + } + + /** + * @template U + * + * @param callable(T): U $map + * + * @return self + */ + public function map(callable $map): self + { + return new self($this->implementation->map($map)); + } + + /** + * @template U + * + * @param callable(T): self $map + * + * @return self + */ + public function flatMap(callable $map): self + { + return $this->implementation->flatMap($map); + } + + /** + * @template U + * + * @param callable(T): U $result + * @param callable(\Throwable): U $error + * + * @return U + */ + public function match(callable $result, callable $error) + { + return $this->implementation->match($result, $error); + } + + /** + * Be aware that this call is not safe as it may throw an exception. + * + * @throws \Throwable + * + * @return T + */ + public function unwrap(): mixed + { + /** @var T */ + return $this->match( + static fn(mixed $value): mixed => $value, + static fn($e) => throw $e, + ); + } + + /** + * @template U + * + * @param callable(\Throwable): self $recover + * + * @return self + */ + public function recover(callable $recover): self + { + return $this->implementation->recover($recover); + } + + /** + * @return Maybe + */ + public function maybe(): Maybe + { + return $this->implementation->maybe(); + } + + /** + * @return Either<\Throwable, T> + */ + public function either(): Either + { + return $this->implementation->either(); + } + + /** + * Force loading the value in memory (only useful for a deferred Attempt) + * + * @return self + */ + public function memoize(): self + { + return $this->implementation->memoize(); + } +} diff --git a/src/Attempt/Defer.php b/src/Attempt/Defer.php new file mode 100644 index 0000000..d883ab3 --- /dev/null +++ b/src/Attempt/Defer.php @@ -0,0 +1,123 @@ + + * @psalm-immutable + * @internal + */ +final class Defer implements Implementation +{ + /** @var callable(): Attempt */ + private $deferred; + /** @var ?Attempt */ + private ?Attempt $value = null; + + /** + * @param callable(): Attempt $deferred + */ + public function __construct(callable $deferred) + { + $this->deferred = $deferred; + } + + public function map(callable $map): self + { + $captured = $this->capture(); + + return new self(static fn() => self::detonate($captured)->map($map)); + } + + public function flatMap(callable $map): Attempt + { + $captured = $this->capture(); + + return Attempt::defer(static fn() => self::detonate($captured)->flatMap($map)); + } + + public function match(callable $result, callable $error) + { + return $this->unwrap()->match($result, $error); + } + + public function recover(callable $recover): Attempt + { + $captured = $this->capture(); + + return Attempt::defer(static fn() => self::detonate($captured)->recover($recover)); + } + + public function maybe(): Maybe + { + $captured = $this->capture(); + + return Maybe::defer(static fn() => self::detonate($captured)->maybe()); + } + + public function either(): Either + { + $captured = $this->capture(); + + return Either::defer(static fn() => self::detonate($captured)->either()); + } + + /** + * @return Attempt + */ + public function memoize(): Attempt + { + return $this->unwrap(); + } + + /** + * @return Attempt + */ + private function unwrap(): Attempt + { + /** + * @psalm-suppress InaccessibleProperty + * @psalm-suppress ImpureFunctionCall + */ + return $this->value ??= ($this->deferred)()->memoize(); + } + + /** + * @return array{\WeakReference>, callable(): Attempt} + */ + private function capture(): array + { + /** @psalm-suppress ImpureMethodCall */ + return [ + \WeakReference::create($this), + $this->deferred, + ]; + } + + /** + * @template A + * + * @param array{\WeakReference>, callable(): Attempt} $captured + * + * @return Attempt + */ + private static function detonate(array $captured): Attempt + { + [$ref, $deferred] = $captured; + $self = $ref->get(); + + if (\is_null($self)) { + return $deferred(); + } + + return $self->unwrap(); + } +} diff --git a/src/Attempt/Error.php b/src/Attempt/Error.php new file mode 100644 index 0000000..d933174 --- /dev/null +++ b/src/Attempt/Error.php @@ -0,0 +1,72 @@ + + * @psalm-immutable + * @internal + */ +final class Error implements Implementation +{ + public function __construct( + private \Throwable $value, + ) { + } + + /** + * @template T + * + * @param callable(R1): T $map + * + * @return self + */ + public function map(callable $map): self + { + /** @var self */ + return $this; + } + + public function flatMap(callable $map): Attempt + { + return Attempt::error($this->value); + } + + public function match(callable $result, callable $error) + { + /** @psalm-suppress ImpureFunctionCall */ + return $error($this->value); + } + + public function recover(callable $recover): Attempt + { + /** @psalm-suppress ImpureFunctionCall */ + return $recover($this->value); + } + + public function maybe(): Maybe + { + return Maybe::nothing(); + } + + public function either(): Either + { + return Either::left($this->value); + } + + /** + * @return Attempt + */ + public function memoize(): Attempt + { + return Attempt::error($this->value); + } +} diff --git a/src/Attempt/Implementation.php b/src/Attempt/Implementation.php new file mode 100644 index 0000000..0afc68d --- /dev/null +++ b/src/Attempt/Implementation.php @@ -0,0 +1,70 @@ + + */ + public function map(callable $map): self; + + /** + * @template U + * + * @param callable(T): Attempt $map + * + * @return Attempt + */ + public function flatMap(callable $map): Attempt; + + /** + * @template U + * + * @param callable(T): U $result + * @param callable(\Throwable): U $error + * + * @return U + */ + public function match(callable $result, callable $error); + + /** + * @template U + * + * @param callable(\Throwable): Attempt $recover + * + * @return Attempt + */ + public function recover(callable $recover): Attempt; + + /** + * @return Maybe + */ + public function maybe(): Maybe; + + /** + * @return Either<\Throwable, T> + */ + public function either(): Either; + + /** + * @return Attempt + */ + public function memoize(): Attempt; +} diff --git a/src/Attempt/Result.php b/src/Attempt/Result.php new file mode 100644 index 0000000..a561f27 --- /dev/null +++ b/src/Attempt/Result.php @@ -0,0 +1,68 @@ + + * @psalm-immutable + * @internal + */ +final class Result implements Implementation +{ + /** + * @param R1 $value + */ + public function __construct( + private mixed $value, + ) { + } + + public function map(callable $map): self + { + /** @psalm-suppress ImpureFunctionCall */ + return new self($map($this->value)); + } + + public function flatMap(callable $map): Attempt + { + /** @psalm-suppress ImpureFunctionCall */ + return $map($this->value); + } + + public function match(callable $result, callable $error) + { + /** @psalm-suppress ImpureFunctionCall */ + return $result($this->value); + } + + public function recover(callable $recover): Attempt + { + return Attempt::result($this->value); + } + + public function maybe(): Maybe + { + return Maybe::just($this->value); + } + + public function either(): Either + { + return Either::right($this->value); + } + + /** + * @return Attempt + */ + public function memoize(): Attempt + { + return Attempt::result($this->value); + } +}