Iterators for D
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Wed Nov 8 15:45:29 PST 2006
Benji Smith wrote:
> Daniel Keep wrote:
>
>> Things that need random access override opIndex and opIndexAssign.
>>
>> Things which you can take a range of values from override opSlice and
>> opSliceAssign.
>>
>> Things that require lock-step iteration override opApply, or supply a
>> function that returns a delegate that "runs" a foreach loop.
>>
>> About the only thing this *doesn't* cover are bi-directional iterators
>> (say, iterating back and forth over an infinite series).
>
>
> What about containers where there are multiple valid orders of
> iteration? For a binary tree class, I might want to perform iteration
> using depth-first, breadth-first, in-order, or reverse-order traversals.
> How does the opApply/opApplyReverse solution address these needs?
>
> And isn't a delegate-call about as computationally expensive as a
> virtual method call (in the case of an Iterable iterface)?
It should be roughly equivelant in cost to explicitly calling the method, meaning if the
method is virtual then you will get that cost, and if it is final then it is like any
function call. Since Iterable methods will very likely almost always be virtual, there is
at least a chance of delegates being a little cheaper /some of the time/ -- when they can
be pointers to final methods.
> If the delegate solution is really better than an Iterable interface,
> why create special cases for opApply and opApplyReverse? Why not just
> say that foreach always requires an iteration delegate?
>
> --benji
Well, when foreach(;) was first added to D, I don't think anyone had thought about
delegates-as-aggregates yet. In fact, it was just added a couple of versions back. So I
suppose in a sense, opApply*Reverse is just legacy -- though it makes it straight-forward
to iterate simple, linear-only collections.
I suppose it would be safe enough to do away with opApply*Reverse now, but I don't think
it hurts anything to leave them be, either.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list