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 12:50:48 PDT 2013


On Thursday, October 24, 2013 21:09:25 deadalnix wrote:
> range.map!(a => new Aboject(a))
> 
> And here you go. The delegate passed is pure.

If you don't care about each call to front returning a completely new object, 
then that works, but it pretty much violates the idea that front is supposed 
to be emulating a member variable. front should be logically const and 
logically pure because those are the semantics of reading a member variable. 
And as front is generally treated just like member variable (including getting 
called multiple times between calls to popFront), doing anything with front 
that does not work when multiple calls to front are made between calls to 
popFront is going to be buggy.

Now, it's a good idea to try and minimize the number of calls to front inside 
a function in case the cost is higher than would be desirable (e.g. if map's 
lambda is not cheap), but the semantics of front are expected to be 
essentially those of a member variable, and that means that it's very 
precarious if multiple calls to front do not return the exact same object or 
if they have any side effects.

- Jonathan M Davis


More information about the Digitalmars-d mailing list