D code length vs other languages

mipri mipri at minimaltype.com
Sat Dec 7 10:17:46 UTC 2019


On Saturday, 7 December 2019 at 09:59:01 UTC, Tobias Pankrath 
wrote:
> On Friday, 6 December 2019 at 20:09:46 UTC, Paolo Invernizzi 
> wrote:
>> Maybe you are both right ... and maybe I've written too much 
>> Python code in the past years and indeed, UFCS chains are a 
>> killer future of D: every list comprehension was turned into a 
>> nice UFCS chain.
>>
>> Let's forget about that: the point is still taken by D, 
>> converting python code in D code is a pleasant experience!
>
> What I miss though is creating ranges with something like 
> python's generator functions.

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]);
       }
   }



More information about the Digitalmars-d mailing list