RFC on range design for D2

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed Sep 10 06:07:43 PDT 2008


Bill Baxter wrote:
> But I think you and I are in agreement that it would be easier and
> more natural to think of ranges as iterators augmented with
> information about bounds, as opposed to a contiguous block of things
> from A to B.

I like that you are bringing this point up, it is interesting. Note that 
my API never assumes or requires that there's an actual contiguous block 
of things underneath. Au contraire, in the I/O case, there's only "the 
current element" underneath.

But a better example is generators. Consider a function generate that 
takes a string expression using a[0], a[1],... a[k] (the state) and 
returns a[k+1]. The generate function also takes the initial state. Then 
generate returns a range that returns in turn each element of the series.

Generate is easy to implement, but I don't want to get into that now, 
only into usage. Simplest use is:

auto boring = generate!("a[0]"(42);

This guy will generate the series 42 42 42 42 42 42 42... forever and 
ever. Now to use it at all we'd have to temper it. So we use function 
called "take", which accepts a maximum size. And then:

writeln(take(10, boring));

This guy will print "42 42 42 42".

Let's generate a more interesting series. How about an iota:

writeln(take(4, generate!("a[0] + 2")(5)));

That guy prints "5 7 9 11". Or Newton's square root approximations:

writeln(take(4, generate!("(a[0] + 2/a[0])/2")(1.0)));

which prints "1 1.5 1.4167 1.4142". All of these are ranges, some 
bounded and some unbounded, but do not have blocks of elements 
underneath them.

>> well these are the operations that you can do on basically all iterators
>> (and with wich you can define new iterators).
>> The one you propose need an underlying total order that can be efficiently
>> checked, for example iterators on trees do not have necessarily this
>> property, and then getting your kind of intersection can be difficult (and
>> not faster than the operation using atSamePlace.
> 
> I don't think that's correct.  Andrei's system does not need a total
> order any more than yours does.  The unions and diffs just create new
> ranges by combining the components of existing ranges.  They don't
> need to know anything about what happens in between those points or
> how you get from one to the other.  Just take the "begin" of this guy
> and put it together with the "end" of that guy, for example.  It
> doesn't require knowing how to get from anywhere to anywhere to create
> that new range.

Yes, that's exactly right.

Andrei


More information about the Digitalmars-d-announce mailing list