foreach, an analogy

Gregor Richards Richards at codu.org
Thu Oct 19 08:46:59 PDT 2006


Walter Bright wrote:
> Gregor Richards wrote:
> 
>> The bigger door is 'for'.  'foreach' is nothing but a convenient 
>> wrapper around 'for'.  And don't you OOphiles go telling me that your 
>> fancy class foo that has iteration /needs/ 'foreach':
>>   for (auto bar = foo.begin(); !(bar is null); bar = foo.iterate(bar))
>> Is it less pretty than foreach?  Yeah.  That's why foreach exists.  
>> But don't go saying that the reverse foreach is a band-aid patch, 
>> because both forms are just convenience wrappers around the far more 
>> powerful and useful 'for'.
> 
> 
> The C++ iterator approach has a serious problem: collections need to be 
> linearized. This is not reasonable for some types of collections, such 
> as a binary tree, which really wants to be traversed in a recursive 
> descent fashion, rather than linearly.

A slight modification can fix that:

  for (auto bar = foo.begin(); !(bar is null); bar = bar.next())


Anyway, my point was merely that 'foreach' is not analogous to the 
too-small-door, since it's merely an alternative to 'for' :)

  - Gregor Richards



More information about the Digitalmars-d-announce mailing list