Arrays\foldR()

higher-order reducer terminal accepts iterable returns Closure pure
((A, T) → A, A) → (Iterable → A)
At a glance — The right fold — useful when ordering affects accumulation. Terminal and must materialise a Generator to iterate backwards.

Creates a Closure that reduces an array or iterable right-to-left, starting from an initial accumulator.

/**
  * @param callable(mixed $carry, mixed $value): mixed $callable
  * @param mixed $initial
  * @return Closure(iterable<int|string, mixed>):mixed
  */
Arrays\foldR(callable $callable, $initial = []): Closure

Returned Closure

When Arrays\foldR() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param iterable<int|string, mixed> $source
  * @return mixed
  */
$function (iterable $source)

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

$joinReversed = Arrays\foldR(fn($acc, $v) => $acc . $v, '');

echo $joinReversed(['a', 'b', 'c']); // cba

Curried

This can be called inline using currying.

echo Arrays\foldR(fn($acc, $n) => $acc - $n, 100)([1, 2, 3]); // 100 - 3 - 2 - 1 = 94

Details

Arrays Functions

Releated Array fold Functions