range properties that work in foreach

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Sat Mar 6 03:15:12 PST 2010


Lars T. Kyllingstad wrote:
> Michael Rynn wrote:
>> On the D2 online pages 
>> (http://www.digitalmars.com/d/2.0/statement.html#ForeachStatement)there 
>> is
>> Foreach over Structs and Classes with Ranges
>>
>>
>> My question is , is there a working example of  foreach ( e ; range )?
>>
>>
>> Iteration over struct and class objects can be done with ranges, which 
>> means the following properties must be defined:
>>
>>
>> Property        Purpose
>> .empty            returns true if no more elements
>> .next            move the left edge of the range right one
>> .retreat        move the right edge of the range left one
>> .head            return the leftmost element of the range
>> .toe            return the rightmost element of the range
>>
>>
>> So I tried this , but foreach did not work, but using the equivalent 
>> for loop code did.
> 
> Looks like you ran into a piece of hopelessly outdated documentation. 
> The correct names are, in the same order:
> 
>   empty
>   popFront
>   popBack
>   front
>   back
> 
> Those should work with foreach.

Actually, when I think about it, I think foreach just needs empty, 
front, and popFront to work.  back and popBack are needed for traversing 
a range in reverse:

    foreach (elem; retro(range)) { ... }

-Lars

-Lars


More information about the Digitalmars-d-learn mailing list