_indexed_ iteration using opApply or range
spir
denis.spir at gmail.com
Sun Dec 12 12:40:44 PST 2010
On Sun, 12 Dec 2010 21:15:00 +0100
"Simen kjaeraas" <simen.kjaras at gmail.com> wrote:
> The trick to ranges is that they modify themselves. For a simple array
> wrapper
> range this may be a way:
>
> struct wrapper( T ) {
> T[] data;
> void popFront( ) {
> data = data[1..$];
> }
> ref T front( ) {
> return data[0];
> }
> bool empty( ) {
> return data.length == 0;
> }
> }
>
> Feel free to ask if you wonder about anything specific.
Thank you, Simen. 2 comments:
(1) In my case, I do not want to modify the range (actually the private collection), because the type is not only about beeing a range (~ provide iteration). So that I defined the range methods, using a private 'rangeIndex slot', as (the type also maintains a 'length' slot):
private uint rangeIndex;
@property void popFront () {
// (re)start...
if (this.rangeIndex >= this.length)
this.rangeIndex = 0;
// ...or move on
else
++ this.rangeIndex;
}
@property bool empty () {
return (this.rangeIndex >= this.length);
}
@property T front () {
return this.stacks[this.rangeIndex];
}
Note that this also enables a restarting feature :-)
(2) How then can I introduce indexed iteration (or more generally iteration with more than one parameter to the block), using ranges? The blocking (!) point is there is no way for front() to return a several multiple results.
I can cheat using a tuple or struct, but D won't understand and unpack it for the user :-) Sure, the user may know I return a pack, but...
Denis
-- -- -- -- -- -- --
vit esse estrany ☣
spir.wikidot.com
More information about the Digitalmars-d-learn
mailing list