Requirements for Slicing Ranges

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Sep 3 19:52:51 UTC 2024


On Tuesday, September 3, 2024 7:42:28 AM MDT Sebastiaan Koppe via Digitalmars-
d wrote:
> On Monday, 2 September 2024 at 11:53:55 UTC, Paul Backus wrote:
> > On Monday, 2 September 2024 at 09:59:04 UTC, Sebastiaan Koppe
> >
> > wrote:
> >> I briefly wondered how it would work if the range is
> >> non-copyable, since taking a slice is effectively taking a
> >> copy of the underlying data the range captures (and its
> >> lifetime).
> >
> > Taking a slice does not necessarily copy the range, nor does it
> > necessarily copy the range's elements.
>
> Apologies, I expressed myself poorly, and I have to admit it is a
> bit of a stretch.
>
> I meant that taking a slice often creates another alias to the
> same data and/or state or part thereof.
>
> This is in contrast to indexing, which just returns the
> underlying item, possible as value.
>
> If you would want to restrict/control a range so much so that you
> make it non-copyable, you could argue you would want to avoiding
> taking a slice from it as well. It might very well have random
> access though, so you would end up with one that exposes indexing
> but not slicing.

Well, with the proposed API, that would not be possible, because the ability
to copy is what differentiates between a basic input range and a forward
range (i.e. copying replaces save), in which case, if you have a
non-copyable range, all you can do is iterate through the elements once. To
have random access would require being a random-access range, which would
require both being a bidirectional range and a forward range, so it would
have to be copyable.

Now, you could still give a basic input range opIndex, since you can have
extra functions on your ranges, but the range API would not consider it a
random-access range, and it would not work with the normal algorithms that
required anything beyond a basic input range.

- Jonathan M Davis





More information about the Digitalmars-d mailing list