p0nce / d-idioms

"Effective D" without the haircut.
http://p0nce.github.io/d-idioms/
81 stars 17 forks source link

Generators (yield return) #101

Open WebFreak001 opened 8 years ago

WebFreak001 commented 8 years ago

https://dlang.org/library/std/concurrency/generator.html

They basically allow the programmer to make every function into a phobos range.

Instead of iterating through stuff and calculating things you could simply use a generator which will only calculate the first thing and then return that one. Once another one is requested it will start from where it stopped.

import std.concurrency;
import std.stdio;
import std.range;

auto generateIntegers()
{
  return new Generator({
    int i = 0;
    while(true) // wont get stuck here
      yield(i++); // because of yield
  });
}

void main()
{
  generateIntegers().take(50).each!writeln;
  // Will print 0-49 to the console
}

More information in other languages: http://www.dotnetperls.com/yield

p0nce commented 8 years ago

Could be in "Phobos gems" article, but probably better in its own article.