sync* generators in Dart
Lazy Iterables: nothing runs until something pulls.
// sync* builds a lazy Iterable; nothing runs until something pulls.
Iterable<int> fibonacci() sync* {
var a = 0, b = 1;
while (true) {
yield a;
(a, b) = (b, a + b);
}
}
Iterable<String> numbered(Iterable<String> items) sync* {
var n = 1;
for (final item in items) {
yield '$n. $item';
n++;
}
}
void main() {
print(fibonacci().take(8).toList());
print(numbered(['scan', 'count', 'log']).join(' '));
}
How it works
sync*plusyieldbuilds anIterableon demand.- An infinite
while (true)is safe —take(8)pulls just eight. (a, b) = (b, a + b)swaps through a record, no temp variable.
Keywords and builtins used here
Stringfinalforinintsyncvarvoidwhileyield
The run, in numbers
- Lines
- 20
- Characters to type
- 402
- Tokens
- 135
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 125 seconds.
Step 3 of 3 in Async, step 24 of 27 in Language basics.