COOL TRICK: (almost) pass-block-as-last-argument

Russell Lewis webmaster at villagersonline.com
Fri Jan 25 13:04:39 PST 2008


Take a look at this main() function.  It looks pretty slick, IMHO:

   void main()
   {
     repeat(10)
       ({
         <code>
       });

     repeat(10, repeat(10))
       ({
         <code>
       });

     // you can nest indefinitely, or mix with other
     // types of loops or modifiers
     repeat(10, repeat(10, repeat(10)))
       ({
         <code>
       });
   }



Here's the implementation of the two versions of repeat:

   void delegate(void delegate()) repeat(int count)
   {
     return delegate void(void delegate() dg)
            {
              for(int i=0; i<count; i++)
                dg();
            }
   }

   void delegate(void delegate())
   repeat(int count, void delegate(void delegate()) subloop)
   {
     return delegate void(delegate void() dg)
            {
              for(int i=0; i<count; i++)
                subloop(dg);
            };
   }



More information about the Digitalmars-d mailing list