Proposal: delegates as aggregates in foreach statements
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Sun May 7 04:21:27 PDT 2006
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.
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list