www.digitalmars.com         C & C++   DMDScript  

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

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);
            };
   }
Jan 25 2008