[Submission] D Slices

Timon Gehr timon.gehr at gmx.ch
Tue May 31 07:17:00 PDT 2011


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

No. I have never met half-open intervals that are open on the left side. All you
have to remember is that the interval is half-open.

> 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).

It is always an error to slice a[i1..i2] with i2<i1. It is a flaw in your code if
you do not know that i1<i2. You can make this sure even if you do not know the
exact bounds.

>
> You will be forced to do smthng like:
>
> if(i1>i2)
>  b=a[i1..i2]
> else
>  b=a[i2..i1]
> end

More semicolons and curly brackets and less "end" please. =)
Your code as is (and if it compiled), will throw an exception in debug or safe
mode if i1!=i2. You understand that?
I also do not get what point you are trying to sell with this snippet, can you
explain what you want to do with i2<i1?

>
> and is easy to forget (several lines below) if a[i1] or a[i2] still
> belongs to the slice or no.

You can always do a[i1..i2+1] to get inclusive slicing.

>
> 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.
int is a keyword.

>
> 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.

It is not wrong, but the right thing to do. I suspect you have not done much
coding (in D) given your code examples.
half-open is the best choice for representing intervals wherever it is possible.
It reduces the amount of +-1 bugs in your code considerably. (try it)


Timon


More information about the Digitalmars-d mailing list