Skip to content

Commit 5c60d8b

Browse files
committed
fix Either and Maybe ::memoize() not loading everything
1 parent b1cc6af commit 5c60d8b

File tree

5 files changed

+55
-2
lines changed

5 files changed

+55
-2
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [Unreleased]
4+
5+
### Fixed
6+
7+
- `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.
8+
39
## 5.10.0 - 2024-11-09
410

511
### Added

proofs/either.php

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
declare(strict_types = 1);
3+
4+
use Innmind\Immutable\Either;
5+
use Innmind\BlackBox\Set;
6+
7+
return static function() {
8+
yield proof(
9+
'Either::memoize() any composition',
10+
given(Set\Type::any()->filter(static fn($value) => !\is_null($value))),
11+
static function($assert, $value) {
12+
$loaded = false;
13+
$either = Either::defer(static fn() => Either::right($value))
14+
->flatMap(static function() use ($value, &$loaded) {
15+
return Either::defer(static function() use ($value, &$loaded) {
16+
$loaded = true;
17+
18+
return Either::right($value);
19+
});
20+
});
21+
22+
$assert->false($loaded);
23+
$either->memoize();
24+
$assert->true($loaded);
25+
},
26+
);
27+
};

proofs/maybe.php

+20
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,24 @@ static function($assert, $value1, $value2) {
4343
);
4444
},
4545
);
46+
47+
yield proof(
48+
'Maybe::memoize() any composition',
49+
given(Set\Type::any()->filter(static fn($value) => !\is_null($value))),
50+
static function($assert, $value) {
51+
$loaded = false;
52+
$maybe = Maybe::defer(static fn() => Maybe::just($value))
53+
->flatMap(static function() use ($value, &$loaded) {
54+
return Maybe::defer(static function() use ($value, &$loaded) {
55+
$loaded = true;
56+
57+
return Maybe::just($value);
58+
});
59+
});
60+
61+
$assert->false($loaded);
62+
$maybe->memoize();
63+
$assert->true($loaded);
64+
},
65+
);
4666
};

src/Either/Defer.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ private function unwrap(): Either
108108
* @psalm-suppress InaccessibleProperty
109109
* @psalm-suppress ImpureFunctionCall
110110
*/
111-
return $this->value ??= ($this->deferred)();
111+
return $this->value ??= ($this->deferred)()->memoize();
112112
}
113113

114114
/**

src/Maybe/Defer.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ private function unwrap(): Maybe
107107
* @psalm-suppress InaccessibleProperty
108108
* @psalm-suppress ImpureFunctionCall
109109
*/
110-
return $this->value ??= ($this->deferred)();
110+
return $this->value ??= ($this->deferred)()->memoize();
111111
}
112112

113113
/**

0 commit comments

Comments
 (0)