Proposal: delegates as aggregates in foreach statements

Chris Nicholson-Sauls ibisbasenji at gmail.com
Sun May 14 11:05:59 PDT 2006


Bruno Medeiros wrote:
> Chris Nicholson-Sauls wrote:
> 
>> An idea occurred to me last night, which I'm sure must have come up 
>> before.  If it hasn't, I'm shocked, but I'm bringing it up (again?) 
>> anyway.  Why not allow a delegate (or even function pointer?) to be 
>> used as the "aggregate" parameter to a foreach statement, requiring 
>> that it expose the same signature as a valid opApply method?  For 
>> example:
>>
>> # class Foo {
>> #   private int[] p_data;
>> #
>> #   int opApply (int delegate(inout size_t, inout int) dg) {
>> #     int result = 0;
>> #     foreach (inout i, inout x; p_data) {
>> #       result = dg(i, x);
>> #       if (result)
>> #         break;
>> #     }
>> #     return result;
>> #   }
>> #
>> #   int reverse (int delegate(inout size_t, inout int) dg) {
>> #     int result = 0;
>> #     foreach (inout i, inout x; p_data.reverse) {
>> #       result = dg(i, x);
>> #       if (result)
>> #         break;
>> #     }
>> #     return result;
>> #   }
>> # }
>> #
>> # Foo foo = new Foo;
>> # foreach (size_t i, int x; &foo.reverse)
>> #   // ... do stuff ...
>>
>> One could even get real cute and use anonymous delegates:
>>
>> # foreach (size_t i, inout char[] x;
>> #   delegate int(int delegate (inout size_t ii, inout char[] xx) {
>> #     // implement iterator logic
>> #   }
>> # ) {
>> #   // ... do stuff ...
>> # }
>>
>> This, I think, would stand in the place of many uses of iterator 
>> objects and mutators.
>>
>> -- Chris Nicholson-Sauls
> 
> 
> Hum, seems like a sound proposal. I think it could be good.
> 
> 

Well at least you thought so.  Doesn't look like it caught anyone else's eye.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list