Prettier iterator implementations in D?

Bill Baxter dnewsgroup at billbaxter.com
Thu Oct 19 20:41:45 PDT 2006


Forgetting about 'foreach' for the moment, I'd like to talk about the 
other end of things: opApply().

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;
     }

seems to be rendered in Ruby-ish D as something like:

     void opApply( ) |inout uint|
     {
	for (int i = 0; i < array.length; i++)
	{
	    yield array[i];
	}
     }

Is there some way to make the real D one look as clean as the Rubified 
one?

Main differences:
1) need to explicitly declare a delegate,
2) need to fiddle with return values.

For 1) I'm thinking if there were only some more compact way to declare 
a delegate it would be golden.

How about this: with function literals, if you leave out the keyword 
'delegate' or 'function' you get a delegate.  I.e.

      int delegate(long c) { return 6 + b; }

is equivalent to

      int (long c) { return 6 + b; }

So it seems logical that as a variable declaration:

      int delegate(long c) dg;

could also be made to be equivalent to

      int (long c) dg;

In that case we could say in D:

     void opApply(void (inout uint) dg)
     {
	for (int i = 0; i < array.length; i++)
	{
	    dg(array[i]);
	}
     }

(assuming that pesky 'int return' business can also be sorted out).

The void can also be omitted frequently in D.  So for a void-returning 
delegate that could even be shortened to:

     void opApply( (inout uint) block)
     {
	for (int i = 0; i < array.length; i++)
	{
	    block(array[i]);
	}
     }

Now *that* is something I wouldn't mind staring at at 3am after a long 
day coding. :-)

--bb



More information about the Digitalmars-d mailing list