Range Redesign: Empty Ranges

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Mar 6 19:19:20 UTC 2024


On Wednesday, March 6, 2024 7:18:50 AM MST Paul Backus via Digitalmars-d 
wrote:
> On Monday, 4 March 2024 at 21:29:40 UTC, Jonathan M Davis wrote:
> > 2. The range API provides no way (other than fully iterating
> > through a range) to get an empty range of the same type from a
> > range unless the range is a random-access range.
>
> Genuine question: what are the use-cases for this?
>
> In general, the capabilities of ranges are designed to serve the
> needs of algorithms. Input ranges exist because single-pass
> iteration is all that's needed to implement algorithms like map,
> filter, and reduce. Random-access ranges exist because they're
> needed for sorting algorithms. And so on.
>
> I'm not aware of any algorithm, or class of algorithm, that needs
> this specific capability you're describing. If such algorithms
> exist, we should be using them to guide our design here. If they
> don't...then maybe this isn't really a problem at all.

There are times where I've had to make a range empty in algorithms in order
to indicate that it's done or force it to be done. This is particularly true
with some algorithms I've written where the range was passed by ref. IIRC, I
tried to add something to std.range for this years ago (either that, or I
tried to make takeNone do it; it's been a while) using the init value, but
Andrei nixed it on the grounds that we couldn't rely on it. The result is
that while we have takeNone, you can't use it to actually make a range
empty. You can just use it to get an empty range of a potentially different
type.

So, while this is not something that I've seen come up frequently, this is
definitely something that I've seen come up in my own code.

And in general, if we're able to require that the init value be empty for
finite ranges, that will reduce the number of bugs surrounding member
variables and the init value, since it's fairly common to end up using the
init value of a range when you have to store it as a member variable (even
if it was a Voldemort type to begin with), and the natural thing to do at
that point is to assume that the init value is empty (even though in
reality, for some range types right now, it isn't even in a valid).

But yes, the desire to have a way to force a range to be empty is something
that's come from actual experience.

- Jonathan M Davis





More information about the Digitalmars-d mailing list