Functions and Records
Records and Destructuring
A record (a, b) groups values without declaring a class. var (x, y) = record destructures them into bindings.
Program
Play the program to return min and max as a record and destructure them.
records_destructure.dart
Replay: real traced execution (multi-file project)
(int, int) minMax(List<int> xs) {
var lo = xs.reduce((a, b) => a < b ? a : b);
var hi = xs.reduce((a, b) => a > b ? a : b);
return (lo, hi);
}
void main() {
var (lo, hi) = minMax([7, 2, 9, 4]);
print('$lo $hi');
}
call ← minMax([7, 2, 9, 4])
7void main() {8 var (lo, hi) = minMax([7, 2, 9, 4]);9 print('$lo $hi');values this stepminMax([7, 2, 9, 4])calllo ← 2
1(int, int) minMax(List<int> xs) {2 var lo = xs.reduce((a, b) => a < b ? a : b);3 var hi = xs.reduce((a, b) => a > b ? a : b);values this step2lo[7, 2, 9, 4]xshi ← 9
2var lo = xs.reduce((a, b) => a < b ? a : b);3var hi = xs.reduce((a, b) => a > b ? a : b);4return (lo, hi);values this step9hi[7, 2, 9, 4]xsreturn value ← (2, 9)
3 var hi = xs.reduce((a, b) => a > b ? a : b);4 return (lo, hi);5}values this step(2, 9)return value2lo9hilo ← 2, hi ← 9
7void main() {8 var (lo, hi) = minMax([7, 2, 9, 4]);9 print('$lo $hi');values this step2lo9hiprint('$lo $hi');
8 var (lo, hi) = minMax([7, 2, 9, 4]);9 print('$lo $hi');10}output2 9values this step2lo9hi
record type
`(int, int)` is a record with two positional fields.
destructuring
`var (lo, hi) = ...` pulls each field into a name.
multiple return
Records let a function return more than one value without a class.