Prettier iterator implementations in D?

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Fri Oct 20 15:57:36 PDT 2006


We could also make the syntax cleaner with type inference. Consider your 
example:

Bill Baxter wrote:
> This code in D:
>     int opApply(int delegate(inout uint) dg)
>     {   int result = 0;
> 
>     for (int i = 0; i < array.length; i++)
>     {
>         result = dg(array[i]);
>         if (result)
>         break;
>     }
>     return result;
>     }

The compiler knows the type of array[i], so it can infer what the type 
of the parameter is. This inference should never be wrong, as long as 
the delegate is called at least once.

The return type can't be inferred, however, so we would combine your 
syntax with type inference to get some hybrid like this:

   int opApply(int (auto) dg)

To handle inout parameters, you simply need inout to be allowed at the 
call-site:

   result = dg(inout array[i]);

C# requires (!) this, and several people have requested that this be 
optional in D -- why shouldn't it?

The only problem I can see with this is that it moves the type of the 
delegate out of the function prototype and into the function. Never mind 
-- many people from functional languages with Hindley-Milner type 
inference have been doing that for years and not had problems with it; 
the saving is more than the gain.



More information about the Digitalmars-d mailing list