Proposal: takeFront and takeBack

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 4 15:07:59 PDT 2012


On Wednesday, July 04, 2012 23:56:33 RivenTheMage wrote:
> > The problem is that while in most cases, separating getting the
> > element referred to by the iterator (or the front of the range)
> > separately
> > from iterating is more efficient than having the iterator
> > return an element when
> > you iterate it
> 
> Yes, but iterators don't need that separation at all. AFAIK,
> that's how iterators work in Java and C++. In C# it's MoveNext()
> and Current, but MoveNext() also checks for emptiness.

C++'s iterators definitely do _not_ return an element when you increment them. 
Nor do they check for emptiness (you have to compare two iterators to do 
that). If you want the element, you must dereference the iterator. And in C#, 
moveNext does not return the element either. Java is the only language that 
I've used which combines iterating and returning the element being iterated to 
or from. Ranges in D could have gone the same route as in Java, but they 
didn't - if nothing else because it's less efficient.

But regardless, iterators have the same choice of either returning an element 
when they iterator not. If they don't return an element, then in general, 
that's more efficient. But if they have to do anything similar to what front and 
popFront must do with strings and calculate their element and/or next 
position, then they're in the same position that we're in with front and 
popFront with strings - except that because the iterator is a separate type, 
it could cache the result of calculating the next code unit when asked for the 
element that it points to. front could do the same thing if it weren't for the 
fact that string is an array rather than a struct.

So, whether it's iterators or ranges really is irrelevant, except for the fact 
that you can't have an iterator which is a string and you _can_ have a range 
which is a string, and it's the fact that the string itself is the range 
rather than another type which makes the caching impossible. The iterating 
itself is the same regardless of whether you're dealing with an iterator or a 
range.

- Jonathan M Davis


More information about the Digitalmars-d mailing list