std.collection - changing the collection while iterating

Joseph Cassman via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 22 08:20:08 PDT 2015


On Monday, 22 June 2015 at 13:42:41 UTC, Steven Schveighoffer 
wrote:
> On 6/22/15 2:27 AM, Joseph Cassman wrote:
>> On Sunday, 21 June 2015 at 23:02:38 UTC, Andrei Alexandrescu 
>> wrote:
[...]
>>
>> I was trying to understand how it could work with array 
>> slices. For
>> example, I was thinking of code similar to the following from 
>> TDPL p. 103:
>>
>> import std.conv, std.stdio;
>> int main(string[] args) {
>>    args = args[1 .. $];
>>    while (args.length >= 2) {
>>      if (to!int(args[0]) != to!int(args[$ - 1])) {
>>        writeln("not palindrome");
>>        return 1;
>>      }
>>      args = args[1 .. $ - 1];
>>    }
>>    writeln("palindrome");
>>    return 0;
>> }
>>
>> Is the slice above considered a range? If so then it seems 
>> that (4) is
>> already used a lot in existing D code. If it is not, then will 
>> slices of
>> the possible future library implementation of arrays be 
>> considered ranges?
>>
>> I cannot see all difficulties arising from allowing (4), but I 
>> imagine
>> code complexity will increase as a result. Perhaps the 
>> compiler can
>> special case arrays to avoid possible issues making (4) 
>> allowable for
>> all containers?
>
> No, what Andrei is referring to is modification of the 
> referenced structure (not just the elements). In other words, 
> imagine removing 5 elements from the array while you are doing 
> this iteration, and pushing all the other elements up.
>
> Modification of the range itself is not ever going to be 
> illegal! A range is for iterating, and if you need to iterate 
> it, you must modify it.
>
> Note also that although the above sample code uses a string 
> which is technically a range, it's not used with range 
> primitives (front back, popFront, popBack), and really it 
> should be used that way to support UTF.
>
> -Steve

Yeah, that's not the input range troika. Wasn't clear on how 
slicing plays into the matter. Thanks Steve.

I think a developer should understand what is trying to do with a 
particular type of collection and so am fine with undefined 
behavior if a collection is modified while iterating. An error 
resulting from such an invalid state does not seem exceptional to 
me, rather a logic error on the part of the developer. So 
exceptions do not seem a fit to me here. I don't like the 
proliferation of try-catch blocks in Java. Would also like to use 
collections in nogc code as well, as much as is possible.

If assistance is added from the compiler a la contracts or 
asserts to catch such logic errors than that is pretty cool. 
Compile-time is a nice plus but if too difficult it could be left 
to the developer's responsibility just fine, IMO.

Joseph



More information about the Digitalmars-d mailing list