foreach, an analogy

Bill Baxter dnewsgroup at billbaxter.com
Tue Oct 24 17:08:02 PDT 2006


renox wrote:
> Jarrett Billingsley wrote:
> 
>> "Bill Baxter" <dnewsgroup at billbaxter.com> wrote in message 
>> news:eh6rva$1anj$2 at digitaldaemon.com...
>>
>>
>>> I think it may be Ruby blocks.
>>
>>
>> They're just anonymous functions which happen to come after the 
>> function call's closing paren.. I wouldn't really say that they're 
>> incredibly earth-shattering or the answer to everything.  And D can 
>> almost do them already.  Instead of:
>>
>> something.each do |item|
>>     puts item
>> end
>>
>> You can have:
>>
>> something.each((int item) {
>>     writefln(item);
>> });
>>
>> In fact the "allowing a trailing function literal" has been proposed 
>> (by myself included), which would allow:
>>
>> something.each()(int item)
>> {
>>     writefln(item);
>> }
> 
> You know, personally I prefer the first way to do it than the second, 
> it's "more orthogonal/clean".

To each his own.  I don't think version 1 would be made illegal or 
anything if the trailing delegate proposal were implemented.  But the 
main difference between them is that version 1 doesn't handle labeled 
break or goto from within the delegate.  Version 2 would presumably 
rewrite the delegate literal in the same way 'foreach' does now.

On the other hand, version 1 works perfectly well with non-literal 
delegates too, and I don't see version 2 ever being made to work that way.

     something.each() foo;

where foo can be any arbitrary expression that evaluates to a delegate, 
is probably never going to be allowed.

> I wonder why it's not used more? It seems quite readable, maybe there is 
> a performance impact (shouldn't happen if the compiler inline the each 
> function call).
> 
> Of course both ways are a little more verbose than Ruby due to the 
> static typing, but they are still very good.

Ok by me if its a little more verbose, as long as the verbosity is 
really the minimal required to make static typing work.

> I wonder if with templates there couldn't be a way to have the "item" 
> element declared implicitely with the correct type?

I think we covered most of the bases in the "Prettier iterator 
implementations in D?" thread in digtalmars.D.  Reiner suggested that 
some types could potentially be deduced and substituted with 'auto'.

--bb



More information about the Digitalmars-d-announce mailing list