Prettier iterator implementations in D?

Alexander Panek a.panek at brainsware.org
Thu Oct 19 23:06:26 PDT 2006


I know Ruby, and it's loops are very cool, indeed. But this is D, and as
a full blown *system and application programming language*, you can't
compare it to Ruby. I don't think syntactic sugar should be added too
hasty. Apart from that I kinda like the delegate / function ptr syntax
as it is.

Alex


On Fri, 2006-10-20 at 12:41 +0900, Bill Baxter wrote:
> 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