foreach without front

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 14 11:24:53 PDT 2014


On 08/14/2014 11:16 AM, Timon Gehr wrote:

 > On 08/14/2014 07:39 PM, Ali Çehreli wrote:
 >> On 08/11/2014 08:40 AM, Jonathan Marler wrote:
 >>
 >>  > I know this is kinda "nit picky" but it would be nice if foreach
 >>  > supported iterating through input ranges without accessing the front
 >>  > function.
 >>  >
 >>  > foreach(myInputRange) {
 >>  >      // myInputRange has a front function but it is
 >>  >      // never called because the foreach has no type list
 >>  > }
 >>
 >> The syntax does not allow that but I have discovered a WAT! :) If you
 >> implement iteration by opApply() member functions, it is possible to use
 >> any random name and it works.
 >>
 >> The following type provides both an int and a void overload.
 >> ...
 >
 > Why would this be surprising?

Because I was taking WAT as a type name. :-/ (jet-lagged here :p)

 > import std.stdio;
 > struct S{
 >      int opApply(int delegate(int) dg){
 >          foreach(i;0..3)
 >              if(int b=dg(i))
 >                  return b;
 >          return 0;
 >      }
 >      int opApply(int delegate() dg){
 >          foreach(i;0..3)
 >              if(int b=dg())
 >                  return b;
 >          return 0;
 >      }
 > }
 >
 > void main(){
 >      auto s = S();
 >      foreach(i; s) writeln(i);
 >      foreach(WAT; s) writeln("_");
 >      // the above is rewritten roughly to the following,
 >      // which is valid code, calling the first opApply overload
 >      switch(s.opApply((WAT){
 >          writeln("_"); return 0;
 >      })){
 >          default: break;
 >      }
 > }
 >
 > This still works if the second opApply overload is removed. The current
 > 'foreach' will never call it.

Makes sense.

Ali



More information about the Digitalmars-d mailing list