[Submission] D Slices

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue May 31 06:48:41 PDT 2011


On 5/31/11 8:29 AM, eles wrote:
>> The right boundary of a slice is exclusive.
>
> I think it should be stated more obvious in the paper.
>
>> This makes sense, so you can
>> do stuff like a[1..$] (== a[1..a.length]) to get a slice that
> contains
>> all elements of a except for the first one (a[0]).
>
> I disagree, but I have not much influence here, although I will
> defend my point of view. I find it quite unpleasant to remember which
> of the left and right bounds are exclusive and, moreover, this
> precludes slicing with a[i1..i2] where i1 and i2 are only known at
> the runtime and may be i2<i1 (and not necessarily i1<i2).
>
> You will be forced to do smthng like:
>
> if(i1>i2)
>   b=a[i1..i2]
> else
>   b=a[i2..i1]
> end
>
> and is easy to forget (several lines below) if a[i1] or a[i2] still
> belongs to the slice or no.

if (i1 > i2) swap(i1, i2);
...

I think it would be a bad application of defensive programming on the 
part of the compiler to liberally allow swapping limits in a slice. Most 
often such situations indicate a bug in the program.

> For example, it would be marvellous to implement definite integral
> convention as: int(a,i1,i2)=sign(i1-i2)*sum(a[i1..i2]) w.r.t. the
> mathematical convention.
>
> For me, the right solution would have been to consider the selection a
> [0..$-1] to select all the elements of the array. This way, "$" still
> means "the length" and one has a clear view of the selection going
> from a[0] to a["length"-1] as expected by someone used to 0-based
> indexes. The slicing would be always inclusive, which is a matter of
> consistence (and goes in line with Walter speaking about the car
> battery). Why to break this convention?
>
> If it is wrong, design it to appear being wrong.

The "war" between open-right and closed-right limit has been waged ever 
since Fortran was first invented. It may seem that closed-right limits 
are more natural, but they are marred by problems of varied degrees of 
subtlety. For example, representing an empty interval is tenuous. 
Particularly if you couple it with liberal limit swapping, what is a[1 
.. 0]? An empty slice or the same as the two-elements a[0 .. 1]? 
Experience has shown that open-right has "won".


Andrei


More information about the Digitalmars-d mailing list