Data Pipeline Patterns
Fold Reduce
Iterable.fold(initial, combine) collapses a list into a single value by carrying an accumulator across the elements. combine is called once per element with (accumulator, element) and returns the next accumulator. The initial value sets the type and starting state of the accumulator. The original list is never modified, and fold finishes with the final accumulator regardless of how many elements were folded.
Program
Play the program to fold [3, 5, 2] into a running sum with (sum, n) => sum + n, then print the result.
fold_reduce.dart
void main() {
var amounts = [3, 5, 2];
var total = amounts.fold(0, (sum, n) => sum + n);
var label = 'total=$total';
print(label);
}
fold
`list.fold(init, combine)` walks the elements left to right, calling `combine(accumulator, element)` and feeding the result back in as the next `accumulator`.
initial value
The initial accumulator sets the type and the starting state. Here `0` keeps the accumulator an `int`; folding into a `String` would start with `''`.
step progression
The trace re-visits the fold line three times to show each `combine` call: `0 + 3 = 3`, `3 + 5 = 8`, `8 + 2 = 10`. The fourth visit binds the final value to `total`.