Automatic Foreach

janderson askme at me.com
Mon Apr 28 00:14:30 PDT 2008


I think people have missed the point on my suggestion.  I wanted 
something that I could use within a template (see example at bottom). 
Something that I could override later or use the overridden case (if 
someone had already written a function to handle arrays of that type).


I often write functions like:

int Covert(int a)
{
...
}


Then endup writing an array version as well.

int[] Convert(int[] a)
{
   int result[];
   result.length = a.length;
   int i=0;
   foreach( ; )
   {
     result [i++];

   }
}

80% of the time the array version is pretty much the same thing.  So a 
while back I wrote a template that works like:

void foo(int i)
{
   printf("B");
}

alias AutoForeach!(foo, int) foo;

Then I could go:

for(6); //Prints "B"
int[] array;
array = 2;
foo(array); //Prints "BB"

But then I couldn't specialize it later without removing the alias, 
because I'd get a name clash.

The other problem is this won't do cases like:

result ~= foo(array);

or

foo(foo1(array));  //Runs foo and foo1 array.length times.


It started cutting my code size down by about 30%.  So I thought it 
might be a good idea for the language.  The language would be able to 
provide provide the candy that you would never be able to get with 
templates.


//////////////////////////////////////////////////
//Use example with templates
//////////////////////////////////////////////////

void print(A ...)(A a)
{
   write(a);
}

print(array1[], array2[], value);

//What happens here is the array is passed into the template, because an 
array is a valid input into a template.  The value is only evaluated 
when inside the template.

So it's equivalent to:

foreach (auto val; array1)
{
   write(val);
}

foreach (auto val; array2)
{
   write(val);
}

write(value);



More information about the Digitalmars-d mailing list