D code length vs other languages
Tobias Pankrath
tobias at pankrath.net
Sat Dec 7 10:49:37 UTC 2019
On Saturday, 7 December 2019 at 10:17:46 UTC, mipri wrote:
> On Saturday, 7 December 2019 at 09:59:01 UTC, Tobias Pankrath
> wrote:
>> [...]
>
> You can use std.range.generate with any random closure:
>
> import std.stdio;
>
> void main() {
> import std.range : take, zip, generate;
>
> auto multiples(int n) {
> int i;
> return generate!({
> return i += n;
> });
> }
>
> foreach (p; zip(multiples(2), multiples(3)).take(5)) {
> writeln(p[0], " ", p[1]);
> }
> }
>
> Or use std.concurrency to get the same control flow:
>
> void main() {
> import std.range : take, zip;
> import std.concurrency : Generator, yield;
>
> auto multiples(int n) {
> return new Generator!int({
> int i;
> while (true) yield (i += n);
> });
> }
>
> foreach (p; zip(multiples(2), multiples(3)).take(5)) {
> writeln(p[0], " ", p[1]);
> }
> }
Didn't know std.concurrency.Generator, thanks!
With std.range.generate I don't know how to signal
exhaustion/emptyness of a range. For simple infinite use cases
it's cool though.
More information about the Digitalmars-d
mailing list