Numbers\accumulatorInt()

accumulator returns Closure pure
int → (int | null → Closure | int)
At a glance — An integer accumulator: each call with an int appends to the running total and returns a fresh accumulator; call with null (or no argument) to finalise and read the total.

Creates a self-returning integer accumulator. Each call with an int returns a new accumulator Closure with that value added to the running total. Call with null (or no argument) to read the accumulated int out.

/**
  * @param int $initial Optional seed value. Defaults to 0.
  * @return Closure(int|null):(Closure|int)
  */
Numbers\accumulatorInt(int $initial = 0): Closure

Returned Closure

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

/**
  * @param int|null $value  Value to add, or null to finalise.
  * @return Closure|int     Closure while still accumulating, int once finalised.
  */
$function (?int $value = null): Closure|int

Examples

Partial Application

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

// Seed the accumulator with a starting value — each call returns a new accumulator.
$total = Numbers\accumulatorInt(100);

// Add values step by step. Every add returns a fresh accumulator.
$total = $total(5);
$total = $total(10);
$total = $total(-3);

// Call with no argument (or null) to read the running total.
echo $total(); // 112

Curried

This can be called inline using currying.

// Chain the calls inline — every () adds; the final empty () finalises.
echo Numbers\accumulatorInt()(1)(2)(3)(4)(); // 10

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

// Fold an array of integers into a single total.
$nums = [5, 10, 15, 20, 25];

$acc = array_reduce(
  $nums,
  fn($acc, $n) => $acc($n),
  Numbers\accumulatorInt()
);

echo $acc(); // 75

Details

Numbers Functions

Releated Number accumulator Functions