D code length vs other languages

Paul Backus snarwin at gmail.com
Sat Dec 7 18:04:12 UTC 2019


On Saturday, 7 December 2019 at 10:49:37 UTC, Tobias Pankrath 
wrote:
> On Saturday, 7 December 2019 at 10:17:46 UTC, mipri 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]);
>>       }
>>   }
>>
>> [...]
>
> 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.

You can use Nullable (or Optional from dub) and a bit of 
post-processing to get a finite range:

import std;

void main()
{
     auto seq(int start, int end)
         in (start <= end)
     {
         int i = start;
         return
             generate!({
                 if (i >= end) { return Nullable!int.init; }
                 else { return nullable(i++); }
             })
             .until!(n => n.isNull)
             .map!(n => n.get);
     }

     writeln(seq(10, 20).array);
}



More information about the Digitalmars-d mailing list