[Submission] D Slices

Nick Sabalausky a at a.a
Tue May 31 13:09:04 PDT 2011


"Nick Sabalausky" <a at a.a> wrote in message 
news:is3hoc$peu$1 at digitalmars.com...
> "eles" <eles at eles.com> wrote in message 
> news:is2qgc$2o7h$1 at digitalmars.com...
>>> 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).
>>
>
> When I first started with D, ages ago, I was skeptical about the half-open 
> slices. It sounded unbalanced. But since then, I've been won over by it 
> for a few reasons (in no particular order):
>
> 1. After years of using D, I've never had a problem with it working that 
> way. And even initially, I found it very easy to learn and get used to it.
>
> 2. I've found it easier to avoid off-by-one errors. I don't have to think 
> about them as much.
>
> 3. arr[a..b].length == b-a     <-- That's a *very* nice, clean, useful 
> property to have. And I think it's one of the main reasons for #2 above. 
> In fact, this actually makes it feel more balanced to me than having 
> inclusive on both ends.
>
> 4. The following:
>
> string str = "ABCDEF";
> int splitIndex = 3;
>
> string part1 = str[0 .. splitIndex];
> string part2 = str[splitIndex .. $];
>
> assert(part1 ~ part2 == str);
>
> Ie, when you split an array, you can use the same index for both halves. 
> No "+1"-ing. It just works. Don't have to think about it.
>

Another way I often like to think of it is, if you'll pardon the ASCII-art, 
a slice looks like this:

  ___________
<___________<

Like stackable cups. They "fit" together. Nice, neat and tidy. But if it 
were inclusive on both ends, it would look like this:

  ___________
<___________>

Those don't fit together. Messy.






More information about the Digitalmars-d mailing list