Arrays\scan()

higher-order transformer lazy accepts iterable returns Closure pure
((A, T) → A, A) → (Iterable → Iterable)
At a glance — Running-fold — every intermediate accumulator value is yielded. Lazy on Generator input.

Creates a Closure that emits each intermediate accumulation of a left-fold over an array or iterable — essentially a "running fold". Starts with the initial value.

/**
  * @param callable(mixed $carry, mixed $value):mixed $function
  * @param mixed $initialValue
  * @return Closure(iterable<int|string, mixed>):(array<int, mixed>|\Generator<int, mixed>)
  */
Arrays\scan(callable $function, $initialValue): Closure

Returned Closure

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

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

Examples

Partial Application

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

$runningTotal = Arrays\scan(fn($acc, $n) => $acc + $n, 0);

print_r($runningTotal([1, 2, 3, 4]));
// [0, 1, 3, 6, 10]

Curried

This can be called inline using currying.

print_r(Arrays\scan(fn($acc, $v) => $acc . $v, '')(['a', 'b', 'c']));
// ['', 'a', 'ab', 'abc']

Details

Arrays Functions

Releated Array fold Functions