New linked list

Oskar Linde oskar.lindeREM at OVEgmail.com
Wed May 24 01:58:59 PDT 2006


Derek Parnell skrev:
> On Wed, 24 May 2006 08:47:21 +0200, Frits van Bommel wrote:
> 
>> Boris Wang wrote: [edited upside-down post]
>>> "Walter Bright" <newshound at digitalmars.com> 写入消息新闻:e3vq3l$1rp5$3 at digitaldaemon.com...
>>>> Sean Kelly wrote:
>>>>> Very cool.  One thing... does this work:
>>>>>
>>>>>     foreach( Person p; per.each )
>>>>>     {
>>>>>         if( p.age > 50 )
>>>>>             p.listRemove();
>>>>>     }
>>>>>
>>>>> ie. can you remove elements within a foreach?
>>>> It's undefined behavior. foreach is entitled to assume that the aggregate 
>>>> is a loop invariant, although the contents of the aggregate's elements can 
>>>> change. This precludes things like resizing an array inside a foreach, 
>>>> etc. 
>>  > why not make a feature:
>>  >
>>  >     safe foreach( Person p; ....)
>>
>> If such a feature was to be implemented, I can think of a better 
>> (cleaner and more consistent with the rest of the language) syntax:
>>
>>      foreach(Peron p; inout people)
>>      {
>>          // ...
>>      }
>>
>> Why invent a new keyword when an old one (though in a different place) 
>> perfectly expresses what's going on?
> 
> Yes! 
> 
> The meaning of this would be that "people" would be 're-evaluated' prior to
> each iteration under the assumption that something in the body of the loop
> modified the array in some manner.

By reevaluation, I presume you don't mean that given:

foreach(var; inout Expression),

Expression is reevaluated on each iteration?

What would the semantics be for iteration over a regular array when the 
array is applied the different changing operations?

I.e. what should foreach do if the following is done inside the loop body:

* arr ~= element;
* arr = arr[0..i-1] ~ arr[i+1..$]; // (legal?)
* arr[i] = arr[$-1], arr.length = arr.length-1;
* arr = arr[-1..$];
* arr = otherArr ~ arr;
* more?

I guess the only feasible equivalent of

foreach(x ; inout arr())

would be:

{ auto array = arr();
   for (int i = 0; i < array.length; i++) {
     /*inout*/ auto x = array[i];

But that goes against the "each" in foreach by skipping the next element 
following a deletion and iterating doubly over elements if the array is 
appended to while the loop is running.

/Oskar



More information about the Digitalmars-d-announce mailing list