Questions about the slice operator
Jonathan M Davis
jmdavisProg at gmx.com
Wed Apr 4 10:09:11 PDT 2012
On Wednesday, April 04, 2012 12:06:33 Jacob Carlborg wrote:
> On 2012-04-04 04:11, Jonathan M Davis wrote:
> > foreach(i; 0 .. 5)
> >
> > is more efficient only because it has _nothing_ to do with arrays.
> > Generalizing the syntax wouldn't help at all, and if it were generalized,
> > it would arguably have to be consistent in all of its uses, in which case
> >
> > foreach(i; 0 .. 5)
> >
> > would become identical to
> >
> > foreach(i; [0, 1, 2, 3, 4])
> >
> > and therefore less efficient. Generalizing .. just doesn't make sense.
>
> Why couldn't the .. syntax be syntax sugar for some kind of library
> implement range type, just as what is done with associative arrays.
>
> We could implement a new library type, named "range". Looking something
> like this:
>
> struct range
> {
> size_t start;
> size_t end;
> // implement the range interface or opApply
> }
>
> range r = 1 .. 5;
>
> The above line would be syntax sugar for:
>
> range r = range(1, 5);
>
> void foo (range r)
> {
> foreach (e ; r) {}
> }
>
> foo(r);
That might work, but it does make it so that ".." has very different meanings
in different contexts, and I don't know that it really buys us much. iota
already does them same thing (and with more functionality), just without the
syntactic sugar. Also, we've had enough issues with moving AA's into druntime,
that I don't know how great an idea this sort of thing would be (though it
should be much simpler). It would certainly make some folks (e.g. Bearophile)
happy though.
> This could then be taken advantage of in other parts of the language:
>
> class A
> {
> int opSlice (range r); // new syntax
> int opSlice (size_t start, size_t end); // old syntax
> }
>
> I think this would be completely backwards compatible as well.
Except that opSlice already works with "..". What would this buy you? It
doesn't make sense to pass opSlice a range normally. Why treat this proposed
"range" type any differently from any other range? This functionality already
exists with the second declaration there. If we added a range type like this,
I'd be inclined to make it __range or somesuch and not ever have its name used
explicitly anywhere. It would basically just be syntactic sugar for iota
(though it wouldnt' use iota specifically). I don't know what else you would be
looking to get out of using its type specifically anywhere. That's not general
done with other range types.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list