[Submission] D Slices

eles eles at eles.com
Tue May 31 08:10:59 PDT 2011


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

That will affect further values from that point onward, which could
not be necessarily intended.
Also, is a bit of overhead for solving such a little issue. OK, it is
simple to swap but... why to be force to do it?

> 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

I agree that the issue is not simple (else, there would have been no
"war"). I know no other examples where open-right limits are used. I
use (intensively) just another language capable of slicing, that is
Matlab. It uses the closed-left and closed-right limits and I tend to
see it as a winner in the engineering field, precisely because of its
ability to manipulate arrays (its older name is MATrix LABoratory and
this is exaxtly why I am using it for). Some examples of syntax
(arrays are 1-based in Matlab):

a=[1,2,3,4]; % array with elements: 1, 2, 3, 4 (of length 4)
b=a(1:3); %b is an array with elements: 1, 2, 3 (of length 3)
c=a(end-1:end); %c is an array with elements: 3, 4 (of length 2)
d=a(2:1); %d is empty
e=a(1:end); %e is an array with elements: 1,2,3,4 (of length 4)
f=a(1:10); %ERROR (exceeds array dimension)
g=a(1:1); %g is an array with elements: 1 (of length 1)

Although there is no straight way to represent an empty array using
the close-left&right syntax, I doubt this is important in real world.
Matlab has a special symbol (which is "[]") for representing empty
arrays. Where the need to represent an empty interval using slice
syntax in D?

Moreover, when writing in D: a[1..1] is this an empty or a non-empty
array? One convention says that the element a[1] is part of the
slice, since the left limit is included and the other convention says
a[1] is not part of the slice precisely because the right limit is
excluded. So, which one weights more? So, is a[1..1] an empty array
or an array with one element?

However, in syntax consistency, for me a[0..$-1] has the main
advantage of not inducing the feeling that a[$] is an element of the
array. Elements are counted from 0 to $-1 ("length"-1) and the syntax
a[0..$-1] is just a confirmation for that (ie. "counting all
elements").

I am sorry, but I tend to follow the Matlab convention. If there is a
field where Matlab is really strong (besides visualization), is
matrix and array operation. A standard document about what Matlab is
able to do is: http://home.online.no/~pjacklam/matlab/doc/mtt/doc/
mtt.pdf







More information about the Digitalmars-d mailing list