std.range.cacheFront proposal&working code: wraps a range to enforce front is called only once

Jonathan M Davis jmdavisProg at gmx.com
Thu Oct 24 10:52:34 PDT 2013


On Thursday, October 24, 2013 17:55:22 Chris wrote:
> On Thursday, 24 October 2013 at 15:40:22 UTC, Dicebot wrote:
> > On Thursday, 24 October 2013 at 15:36:59 UTC, Chris wrote:
> >> How do you define side effects? After all ranges manipulate,
> >> reformat or restructure data.
> > 
> > They should do it in popFront. I'd consider any `front` that
> > does anything but accessing cached value suspicious.
> 
> So code like
> 
> auto front() {
> doSomething();
> return range[0];
> }
> 
> should go into
> 
> void popFront() {
> doSomething();
> range = range[1..$];
> }

Yes. front _will_ be called multiple times by many range-based algorithms. 
There are no guarantees whatsoever that front will not be called more than 
once and relying on it being called only once between calls to popFront is 
just plain wrong.

front is the logical equivalent to a public member variable and should be 
treated as such. In general, putting additional work inside of front is just
asking for trouble. And if you do, it needs to be with the understanding
that front stands a good chance of being called multiple times per call to
popFront.

It might make sense to add some debug stuff in there which has side effects 
(like printing something out), but the code's normal semantics should not
rely on any kind of side effects on front. There should be no logical
difference if you call front one time or twenty times after a single call to
popFront.

- Jonathan M Davis


More information about the Digitalmars-d mailing list