/
FoldRight.php
54 lines (49 loc) · 1.75 KB
/
FoldRight.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare(strict_types=1);
namespace loophp\collection\Operation;
use Closure;
use Generator;
use Iterator;
/**
* @psalm-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
*
* phpcs:disable Generic.Files.LineLength.TooLong
*/
final class FoldRight extends AbstractOperation
{
/**
* @psalm-return Closure(callable(T|null, T, TKey, Iterator<TKey, T>): T): Closure(T|null): Closure(Iterator<TKey, T>): T|null
*/
public function __invoke(): Closure
{
return
/**
* @psalm-param callable(T|null, T, TKey, Iterator<TKey, T>): T $callback
*/
static function (callable $callback): Closure {
return
/**
* @param mixed|null $initial
* @psalm-param T|null $initial
*/
static function ($initial = null) use ($callback): Closure {
return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<int, T|null>
*/
static function (Iterator $iterator) use ($callback, $initial): Generator {
/** @psalm-var callable(Iterator<TKey, T>): Generator<TKey, T> $foldRight */
$foldRight = Compose::of()(
Reverse::of(),
FoldLeft::of()($callback)($initial)
);
return yield from $foldRight($iterator);
};
};
};
}
}