Foreach Closures?

Timon Gehr timon.gehr at gmx.ch
Sun Apr 8 16:45:05 PDT 2012


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


More information about the Digitalmars-d mailing list