RFC on range design for D2

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Sep 9 08:45:53 PDT 2008


Ary Borenszweig wrote:
> Andrei Alexandrescu a écrit :
>> Hello,
>>
>>
>> Walter, Bartosz and myself have been hard at work trying to find the 
>> right abstraction for iteration. That abstraction would replace the 
>> infamous opApply and would allow for external iteration, thus paving 
>> the way to implementing real generic algorithms.
>> ...
>> http://ssli.ee.washington.edu/~aalexand/d/tmp/std_range.html
>>
>>
>> Andrei
> 
> It looks very nice, though I have a few questions:
> - Is std.range's source code somewhere? Or it's just the documentation 
> and then the implementation will follow?

There is an implementation that does not compile :o|.

> Because...
> - How do you create a range? In the documentation it says that "Built-in 
> slices T[] are a direct implementation of random-access ranges", so I 
> guess a built-in slice is already a range.

A slice is a range alright without any extra adaptation. It has some 
extra functions, e.g. ~=, that are not defined for ranges.

> But if that is true...
> - How is "void next(T)(ref T[] range)" implemented? If I pass a built-in 
> slice to it, how does the template store the state of where in the range 
> are we? Or maybe you'd need to do Range!(...) to create a range?

void next(T)(ref T[] range) { range = range[1 .. $]; }

> - What do I do to make a collection implement a range? Do I need to 
> implement the templates in std.range using template conditions?

Oh, much simpler. You don't need to use templates at all if you know the 
type in advance.

// assume a collection of ints
// using old names
struct Collection
{
     struct Range
     {
         bool isEmpty() { ... }
         ref int left() { ... }
         void next() { ... }
     }
     Range all() { ... }
}

Collection c;
foreach (auto r = c.all; !r.isEmpty; r.next)
{
     writeln(r.left);
}

The advantage of the above is not that it offers you looping over your 
collection. The advantage is that your collection now can use many of 
the algorithms in std.algorithm, and others written to use ranges.

Collection.Range is in intimate connection with Collection because it 
understands the mechanism of walking the collection.

Your code won't currently compile because returning ref int from left() 
is not allowed.


Andrei


More information about the Digitalmars-d-announce mailing list