typestar

Iterable chains in Dart

where, map and fold read left to right; toList realizes them.

void main() {
  final wingspansCm = [88.0, 20.5, 210.0, 34.0, 150.0];

  // where filters, map transforms; toList realizes the lazy chain.
  final large = wingspansCm.where((w) => w > 100).toList();
  print('Large birds: $large');

  final inMeters = wingspansCm.map((w) => w / 100).toList();
  print('In meters: $inMeters');

  // fold threads an accumulator through every element.
  final total = wingspansCm.fold(0.0, (sum, w) => sum + w);
  print('Combined span: $total cm');
  print('Any tiny? ${wingspansCm.any((w) => w < 25)}');
}

How it works

  1. where((w) => w > 100) keeps the big wingspans, lazily.
  2. map transforms; the chain stays an Iterable until toList.
  3. fold threads an accumulator; any answers yes-or-no.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
517
Tokens
136
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 117 seconds.

Type this snippet

Step 2 of 3 in Collections, step 11 of 27 in Language basics.

← Previous Next →