RFC on range design for D2

Sean Kelly sean at invisibleduck.org
Tue Sep 9 11:36:06 PDT 2008


Andrei Alexandrescu wrote:
> Lars Ivar Igesund wrote:
>> Andrei Alexandrescu wrote:
>>
>>> A slice is a range alright without any extra adaptation. It has some
>>> extra functions, e.g. ~=, that are not defined for ranges.
>>
>> Aren't slices const/readonly/whatnot and thus ~= not possible without
>> copying/allocation?
> 
> Well there's no change in semantics of slices (meaning T[]) between D1 
> and D2, so slices mean business as usual. Maybe you are referring to 
> strings, aka invariant(char)[]?

I do think it's a fair point that ~= could be considered an operation 
that constructs a new container (an array, in this case) using a range 
(slice) as an initializer.  The weird issue right now is that there is 
effectively no difference between a slice and an array insofar as the 
language or code representation are concerned.  In many instances this 
is an advantage, but it leads to some issues, like the one you describe 
below.

> Anyhow, today's ~= behaves really really erratically. I'd get rid of it 
> if I could. Take a look at this:
> 
> import std.stdio;
> 
> void main(string args[]) {
>     auto a = new int[10];
>     a[] = 10;
>     auto b = a;
>     writeln(b);
>     a = a[1 .. 5];
>     a ~= [ 34, 345, 4324 ];
>     writeln(b);
> }
> 
> The program will print all 10s two times. But if we change a[1 .. 5] 
> with a[0 .. 5] the behavior will be very different! a will grow "over" 
> b, thus stomping over its content.
> 
> This is really bad because the behavior of a simple operation ~= depends 
> on the history of the slice on the left hand side, something often 
> extremely difficult to track, and actually impossible if the slice was 
> received as an argument to a function.
> 
> IMHO such a faux pas is inadmissible for a modern language.

This would be easy to fix by making arrays / slices fatter (by adding a 
capacity field, for example), but I'm still not convinced that's the 
right thing to do.  However, it may well be preferable to eliminating 
appending completely.  The obvious alternative would be either to 
resurrect head const (not gonna happen) or to make append always 
reallocation (not at all ideal).


Sean


More information about the Digitalmars-d-announce mailing list