Consevutive calls to r.front

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 7 22:53:59 PDT 2015


On Monday, June 08, 2015 13:51:18 Mike Parker via Digitalmars-d-learn wrote:
> On 6/8/2015 12:43 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> > On Monday, June 08, 2015 00:42:07 Mike Parker via Digitalmars-d-learn wrote:
> >> When implementing a custom range, is it correct to say that
> >> consecutive calls to r.front with no intervening calls to
> >> popFront should return the same value? Seems like I read
> >> something along those lines before, but I can't find it anywhere.
> >
> > Yes. I was actually talking with Walter about this at dconf. Two consecutive
> > calls to front must return equivalent values (but not necessarily exactly
> > the same object - e.g. map!((a) => to!string(a))(range) is going to return
> > equal strings, but they won't be the exact same string). It would be a
> > fundamental violation of the range concept for multiple calls to front
> > to return values that were not equal if popFront were not called in between.
> >
> > Also, a range cannot depend on empty or front being called in order to
> > iterate correctly. It _can_ choose to do work in those functions instead of
> > just popFront (e.g. map does), but it has to work to just have popFront
> > called without calling empty or front (e.g. if you know that the range has
> > more than 10 elements, you should be free to call popFront 10 times without
> > checking empty or accessing front).
> >
> > - Jonathan M Davis
> >
> Thanks, Jonathan. That's what I was looking for.

Though I should probably note that calling front or popFront when empty is
true is undefined behavior. We've taken to doing stuff like

    version(assert) if(empty) throw new RangeError;

in Phobos in front and popFront, but you can't rely on any particular
behavior if you call front or popFront on an empty range. So, you can skip
calls to empty if you _know_ that the range isn't empty, but if you don't
know, then you're risking undefined behavior if you call front or popFront
without checking empty.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list