Array Slice Ranges

Pragma ericanderton at yahoo.removeme.com
Thu Nov 9 12:46:07 PST 2006


%u wrote:
> I'm learning ruby right now, and I noticed they use a very cool syntax for ranges.
> 
> 0..5 means 0, 1, 2, 3, 4, 5
> 0...5 means 0, 1, 2, 3, 4
> 
> The current array slicing is useful half the time and a pain in the arse the
> other half, so I was wondering if anyone else has mentioned this idea for D
> before...
> 
> - Trevor

I hope you don't mind, but I'm just thinking aloud here.

I like the idea, and it has been brought up before on multiple 
occasions.  But I don't think the syntax is going to stand up to 
scrutiny for a lot of reasons (many were already voiced in earlier 
posts). My feeling is that it's not clearly distinguished from ".." 
which is important since ".." only ever appears within the same context.

Something that triggers a "create range" expression might be clearer:

auto myRange = @[0..10];

...distinguishing from uint and int ranges is another problem.  The 
actual "type" installed is another, which leads me into the main thrust 
of this post: I don't think the creation syntax is the main stumbling 
block for the inclusion of a range type into D.

Rather, I feel that the problem is: how would any range type be 
implemented under-the-hood, let alone it's construction syntax?  What 
would it need to be?

I can't help but see it as a pseudo-array type, in order to allow for 
concatenation, slicing, array operations (when and if they're 
implemented), and iteration to all behave correctly.

// assuming ranges play fair with arrays, how would these work?
foreach(x; myRange){}
myRange[1..10];
myRange.dup;
myRange.length;
myRange ~= anotherRange;

The only way to satisfy all of the above cleanly, is as a library type 
that masquerades as an array.  Something like a templated struct could 
do the job nicely, and would cover more range types than just integer 
sequences.  In essence, I think the need for a range type w/array 
semantics, is one-and-the-same with the need for an iterator 
implementation.  They're just two different flavors of the same thing: 
one iterates an actual data set (which built-in arrays do implicitly), 
the other pulls values out of thin air.

-- 
- EricAnderton at yahoo



More information about the Digitalmars-d mailing list