fold and reduce
- Dart course
- Intermediate
- Lesson 49/116
- 5 min
Learn aggregation with fold and reduce.
fold and reduce
fold and reduce reduce a collection to a single value. They are used for sums, products, max and similar computations. Both accumulate elements one by one.
reduce takes no initial value; it uses the first element as the start. fold takes an initial value and is safe on empty collections.
Example: var sum = [1, 2, 3, 4].fold(0, (acc, n) => acc + n);. Here 0 is the initial, acc the accumulator, n the current element. Result: 10.
Product with reduce
reduce takes no initial value. The first element is treated as the start and accumulation begins from the second. On an empty collection reduce throws.
Example: var product = [1, 2, 3, 4].reduce((a, b) => a * b);. Here a is the accumulator, b the current. Steps: 1*2=2, 2*3=6, 6*4=24. Result: 24.
fold is safer because you give an initial value. reduce is shorter to write and preferred for non-empty collections.
Practice Compute sum and product
On the list [1, 2, 3, 4] compute the sum with fold(0, (acc, n) => acc + n) and print it. On the same list compute the product with reduce((a, b) => a * b) and print it.
Starter code
void main() {
var numbers = [1, 2, 3, 4];
// compute sum with .fold and product with .reduce, print both
}Sample solution
void main() {
var numbers = [1, 2, 3, 4];
var sum = numbers.fold(0, (acc, n) => acc + n);
var product = numbers.reduce((a, b) => a * b);
print(sum);
print(product);
}Expected output
10 24
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the fold parts
| Term | Meaning |
|---|---|
0 |
Initial value |
acc |
Accumulator |
n |
Current element |
acc + n |
Accumulation step |
2 What is the difference between fold and reduce?
- fold takes an initial value, reduce does not Correct answer
- reduce is faster
- fold works only on lists
- They are exactly the same
Explanation: fold takes an initial value, reduce uses the first element.
3 The fold call
var numbers = [1, 2, 3, 4];
var sum = numbers.____(0, (acc, n) => acc + n);
var numbers = [1, 2, 3, 4];
var sum = numbers.fold(0, (acc, n) => acc + n);
Explanation: fold reduces with an initial value.