Foreach Closures?

Kevin Cox kevincox.ca at gmail.com
Sun Apr 8 16:52:20 PDT 2012


On Apr 8, 2012 7:49 PM, "Timon Gehr" <timon.gehr at gmx.ch> wrote:
>
> On 04/09/2012 01:26 AM, Kevin Cox wrote:
>>
>> I was wondering about the foreach statement and when you implement
>> opApply() for a class it is implemented using closures.  I was wondering
>> if this is just how it is expressed or if it is actually syntatic
>> sugar.  The reason I aski is because if you have a return statement
>> inside a foreach it returns from the outside function not the "closure".
>>
>> I was just wondering if anyone could spill the implementation details.
>>
>> Thanks,
>> Kevin
>
>
> Since opApply has to hand through the return code if it is non-zero, I
assume that DMD simply generates a custom exit code for each possible way
the foreach body can be exit from.
>
> eg:
>
> start:
> foreach(x; foo){
>    if(x==1) break;
>    else if(x==2) return 10;
>    else if(x==3) goto start;
>    else if(x==4) continue;
>    ...
> }
>
> ==>
>
> int __result;
> start:
> switch(foo.opApply((x){
>    if(x==1) return 1;
>    else if(x==2){__result = 10; return 2;}
>    else if(x==3) return 3;
>    else if(x==4) return 0;
>    ...
> }){
>    case 0, 1: break;
>    case 2: return __result;
>    case 3: goto start;
> }

Cool, so it basically translates break and continue to returns and returns
to black magic.  Cool.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20120408/69917714/attachment.html>


More information about the Digitalmars-d mailing list