Proposal: takeFront and takeBack

Wouter Verhelst wouter at grep.be
Tue Jul 3 10:21:42 PDT 2012


Jonathan M Davis <jmdavisProg at gmx.com> writes:

> This seems like it probably merits a bit of discussion, so I'm bringing it up 
> here rather than simply opening a pull request.
>
> At present, for some ranges (variably-lengthed ranges such as strings in 
> particular), calling front incurs a cost which popFront at least partially 
> duplicates. So, the range primitives are inherently inefficient in that they 
> force you to incur that extra cost as you iterate over the range. Ideally, 
> there would be a way to get front and pop it off at the same time so that you 
> incur the cost only once (either that or have front cache its result in a way 
> that lets it avoid the extra cost in popFront when popFront is called - though 
> that wouldn't work with strings, since for them, the range primitives are free 
> functions). So, I'm proposing takeFront and takeBack:
>
> https://github.com/jmdavis/phobos/commit/5bfa8126fa14a539fee67807821ec0a10503f27b
>
> For most ranges, takeFront does this:
>
> auto takeFront(R)(ref R range)
>     if(isInputRange!R && !isNarrowString!R)
> {
>     assert(!range.empty);
>     auto retval = range.front;
>     range.popFront();
>     return retval;
> }

Couldn't you just overload popFront?

have a void popFront which throws off the first element without
returning anything, and an auto popFront which does return data.

I'd always been taught that "pop" means "read a bit and chop it off",
which means that having to first read the front and then pop it off
(i.e., in two separate methods) feels rather counterintuitive to
me. That's in addition to the fact that yes, there's a performance
issue.

But hey, I've only been doing this D thing for a few weeks, so feel free
to ignore me if I'm not making any sense :-)

-- 
The volume of a pizza of thickness a and radius z can be described by
the following formula:

pi zz a


More information about the Digitalmars-d mailing list