A problem with generators

Lutger lutger.blijdestijn at gmail.com
Wed Mar 17 14:53:16 PDT 2010


bearophile wrote:

> D currently has two ways to define a generator, the first is the older one
> with opApply (And opApplyReverse): int opApply(int delegate(ref Type [,
> ...]) dg);
> 
> 
> The syntax of opApply is terrible: hard to remember, bug-prone, noisy,
> intrusive. And this syntax doesn't even gain performance, because dmd is
> not very good at inlining here. Several times in the past I have said that
> a very good syntax for this is the Python one:
> 
> def foo():
>   yield 5
> 
> It's really easy to use and remember, not bug prone. This possible syntax
> is about 75 times better than the current opApply:
> 
> yield(int) foo() {
>   yield 5;
> }
> 
> 
> That's sugar for something like:
> 
> struct foo {
>     int opApply(int delegate(ref int) dg) {
>         int result;
>         int r = 5;
>         result = dg(r);
>         if (result)
>             goto END;
>       END:
>         return result;
>     }
> }
> 

Hi, is this generator thing really the same as opApply? I thought this is  
more like co-routines. Can yield be as efficient as current opApply? 
(assuming inlining will eventually happen where possible)

The tango docs have/had a good discussion about opApply vs Iterator, where 
the author called opApply a visitor iirc. Unfortunately the part about 
generators was never finished.

yield may be easy to understand once you understand it :) It's prettier for 
sure. But take a glimpse at this page on stackoverflow, the length of the 
answers should tell you that it's not as straightforward as you might think 
and that it's not only about the syntax:

http://stackoverflow.com/questions/231767/can-somebody-explain-me-this-
python-yield-statement




More information about the Digitalmars-d mailing list