Collections
Lists
Add and Reduce
A list literal [1, 2, 3] builds an ordered collection. add appends, and reduce folds with a closure.
Program
Play the program to append a value and sum the list.
lists.dart
Replay: real traced execution (multi-file project)
void main() {
var nums = [1, 2, 3];
nums.add(4);
var total = nums.reduce((a, b) => a + b);
print(total);
}
nums ← [1, 2, 3]
1void main() {2 var nums = [1, 2, 3];3 nums.add(4);values this step[1, 2, 3]numsnums ← [1, 2, 3, 4]
2var nums = [1, 2, 3];3nums.add(4);4var total = nums.reduce((a, b) => a + b);values this step[1, 2, 3] → [1, 2, 3, 4]numstotal ← 10
3nums.add(4);4var total = nums.reduce((a, b) => a + b);5print(total);values this step10total[1, 2, 3, 4]numsprint(total);
4 var total = nums.reduce((a, b) => a + b);5 print(total);6}output10values this step10total
Add, Then Reduce
- Start with
nums:[1, 2, 3]. nums.add(4)appends4to the end.reducecombines the list from left to right.- The final total is
10. | Step | Values | | --- | --- | | start |[1, 2, 3]| | afteradd(4)|[1, 2, 3, 4]| | reduce total |10|
list literal
`[1, 2, 3]` builds a `List<int>`.
add
`add(x)` appends `x` in place.
reduce
`reduce((a, b) => a + b)` folds the list to one value.
Exercise: lists.dart
Append one number to a list, reduce the list to a total, and print the total