Skip to content

Commit

Permalink
fix Either and Maybe ::memoize() not loading everything
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Dec 1, 2024
1 parent b1cc6af commit 5c60d8b
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## [Unreleased]

### Fixed

- `Innmind\Immutable\Maybe::memoize()` and `Innmind\Immutable\Either::memoize()` was only unwrapping the first layer of the monad. It now recursively unwraps until all the deferred monads are memoized.

## 5.10.0 - 2024-11-09

### Added
Expand Down
27 changes: 27 additions & 0 deletions proofs/either.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
declare(strict_types = 1);

use Innmind\Immutable\Either;
use Innmind\BlackBox\Set;

return static function() {
yield proof(
'Either::memoize() any composition',
given(Set\Type::any()->filter(static fn($value) => !\is_null($value))),
static function($assert, $value) {
$loaded = false;
$either = Either::defer(static fn() => Either::right($value))
->flatMap(static function() use ($value, &$loaded) {
return Either::defer(static function() use ($value, &$loaded) {
$loaded = true;

return Either::right($value);
});
});

$assert->false($loaded);
$either->memoize();
$assert->true($loaded);
},
);
};
20 changes: 20 additions & 0 deletions proofs/maybe.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,24 @@ static function($assert, $value1, $value2) {
);
},
);

yield proof(
'Maybe::memoize() any composition',
given(Set\Type::any()->filter(static fn($value) => !\is_null($value))),
static function($assert, $value) {
$loaded = false;
$maybe = Maybe::defer(static fn() => Maybe::just($value))
->flatMap(static function() use ($value, &$loaded) {
return Maybe::defer(static function() use ($value, &$loaded) {
$loaded = true;

return Maybe::just($value);
});
});

$assert->false($loaded);
$maybe->memoize();
$assert->true($loaded);
},
);
};
2 changes: 1 addition & 1 deletion src/Either/Defer.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private function unwrap(): Either
* @psalm-suppress InaccessibleProperty
* @psalm-suppress ImpureFunctionCall
*/
return $this->value ??= ($this->deferred)();
return $this->value ??= ($this->deferred)()->memoize();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Maybe/Defer.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private function unwrap(): Maybe
* @psalm-suppress InaccessibleProperty
* @psalm-suppress ImpureFunctionCall
*/
return $this->value ??= ($this->deferred)();
return $this->value ??= ($this->deferred)()->memoize();
}

/**
Expand Down

0 comments on commit 5c60d8b

Please sign in to comment.