"isDroppable" range trait for slicing to end
Jonathan M Davis
jmdavisProg at gmx.com
Tue Oct 30 21:48:50 PDT 2012
On Monday, October 29, 2012 15:33:00 monarch_dodra wrote:
> More often than not, we want to slice a range all the way to the
> end, and we have to use the clumsy "r[0 .. r.length]" syntax.
>
> What's worst is that when a range is infinite, there is no real
> way to "slice to the end", unless you just repeatedly popFront.
As already pointed out, this is solved by opDollar. We don't have a trait for
it, but it can be tested for easily enough by doing something like
typeof(is(r[0 .. $])) or __traits(compiles, r[0 .. $]). We may still want to
create a trait for it though (e.g. hasOpDollar).
> I'd like to introduce a new primitive: "popFrontN". You may
> recognize this as a standalone function if range.d: It is. I
> propose we improve this semantic by allowing ranges to directly
> implement this function themselves.
They can do so already, and if UFCS is used, then their version will be used.
We _could_ go a step further and make it so that popFrontN calls a range's
popFrontN if it has one to make it so that it's always used if it exists. The
main problem is that you can't rely on the complexity of popFrontN being
better than O(n), because that's what it's going to be with non-sliceable
ranges. A trait such as isDroppable would fix that, but it's really only an
issue with infinite ranges.
Finite ranges which could have n elements popped in O(1) would be sliceable
anyway, meaning that popFrontN would be O(1) for them already and that if a
function requires popping n elements in O(1), it can just slice the range. So,
isDroppable buys us nothing for finite ranges. The only gain that I really see
here is that it would provide a way for infinite ranges to pop off their first n
elements and still be infinite. As it stands, the best that you can do is slice
them, but that has to result in another range type, because a finite slice
can't be infinite.
However, if we take advantage of opDollar, then I think we can solve the
problem that way. By using opDollar when slicing an infinite range, you should
be able to keep the original range type. That being the case, I don't think
that isDroppable is really necessary. Howevere, it _does_ mean that I should
probably adjust my pull for hasSlicing so that it tests that slicing an
infinite range with opDollar returns the original type (assuming that opDollar
compiles for it). Of course, once opDollar works (I don't know what it's
current state is), it would be desirable to require it to work with slicing
anyway, so maybe hasSlicing should have that requirement added at a later
date.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list