dart-lang / site-www

Source for Dart website
https://dart.dev
Other
944 stars 684 forks source link

Suggest adding main() code to exercise example code for the generators on the 'Functions' page #5729

Open dtonhofer opened 4 months ago

dtonhofer commented 4 months ago

Page URL

https://dart.dev/language/functions/

Page source

https://github.com/dart-lang/site-www/tree/main/src/content/language/functions.md

Describe the problem

The explainer for Generators at

https://dart.dev/language/functions#generators

shows ways to create generator Iterable-s or generator Stream-s, but does not give example code for using them.

This may be too verbose for the page, but I suggest just adding a main() to exercise the example code, which is particularly interesting for the case of using a Stream:

For the "synchronous generator function":

Iterable<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) {
    print("Yielding $k in Iterable");
    yield k++;
  }
}

main() async {
  for (var n in naturalsTo(2)) {
    print("Got $n from Iterable");
  }
  print("Bye");
}

which outputs

Yielding 0 in Iterable
Got 0 from Iterable
Yielding 1 in Iterable
Got 1 from Iterable
Bye

For the "asynchronous generator function":

Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) {
    print("Yielding $k in Stream");
    yield k++;
  }
}

main() async {
  var streamOfString =
      asynchronousNaturalsTo(2).map((n) => "Got $n from Stream");
  // The stream is "run" by collecting its elements into a list
  // and await-ing.
  for (var str in await streamOfString.toList()) {
    print(str);
  }
  print("Bye");
}

which outputs

Yielding 0 in Stream
Yielding 1 in Stream
Got 0 from Stream
Got 1 from Stream
Bye

For the yield* generator function (what does it do? tail call optimization?)

Iterable<int> naturalsDownFrom(int n) sync* {
  if (n > 0) {
    print("Yielding $n in Stream based on recursive generator");
    yield n;
    yield* naturalsDownFrom(n - 1);
  }
}

main() async {
  for (var n in naturalsDownFrom(2)) {
    print("Got $n from Iterable based on recursive generator");
  }
  print("Bye");
}

which outputs

Yielding 2 in Stream based on recursive generator
Got 2 from Iterable based on recursive generator
Yielding 1 in Stream based on recursive generator
Got 1 from Iterable based on recursive generator
Bye

Expected fix

No response

Additional context

No response

I would like to fix this problem.

munificent commented 4 months ago

Yeah, showing an example of calling the generator seems like it would help here.