-
-
Notifications
You must be signed in to change notification settings - Fork 13
IEnumerable.aggregate() method
Marcel Kloubert edited this page Sep 28, 2015
·
3 revisions
Applies an accumulator function over the sequence (s. Aggregate()).
public function aggregate(callable $accumulator
[, $defValue = null ]) : mixed;| Name | Type | Description |
|---|---|---|
| $accumulator | [[callable | Callable]] |
| $defValue | mixed | [OPTIONAL] The value to return if sequence is empty. |
The accumulator has the following structure:
function (mixed $currentResult,
mixed $item,
IIndexedItemContext $ctx) : mixed;The current result for the method.
The current item.
The current item context.
The final accumulator value.
use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(1, 2, 3);
$seq2 = Enumerable::fromValues();
$seq3 = Enumerable::fromValues(1, 2, 3);
$accumulator = '($result, $x) => $result += $x';
// 6
$a1 = $seq1->aggregate($accumulator);
// (null)
$a2 = $seq2->aggregate($accumulator);
// 4, because sequences with one element will
// simply return the first element
$a3 = $seq3->aggregate($accumulator);use \System\Linq\Enumerable;
$seq1 = Enumerable::fromValues(1, 2, 3, 4);
$seq2 = Enumerable::fromValues();
$accumulator = function($result, $x) {
return $result *= $x;
};
// 24
$a1 = $seq1->aggregate($accumulator, false);
// (false)
$a2 = $seq2->aggregate($accumulator, false);