suggested change to foreach index

Ameer Armaly ameer_armaly at hotmail.com
Wed Jun 7 18:02:24 PDT 2006


"Regan Heath" <regan at netwin.co.nz> wrote in message 
news:optasxzhwe23k2f5 at nrage.netwin.co.nz...
> On Wed, 7 Jun 2006 20:27:51 -0400, Ameer Armaly <ameer_armaly at hotmail.com> 
> wrote:
>> "BCS" <BCS at pathlink.com> wrote in message
>> news:e67p90$rol$1 at digitaldaemon.com...
>>> I often find my self doing something like this:
>>>
>>> <code>
>>> int i
>>> char[] arr;
>>>
>>> foreach(int j, c; arr)
>>> if(' ' == c)
>>> {
>>> i=j; // copy j out of foreach's scope
>>> break;
>>> }
>>>
>>> if(i < arr.length)
>>> {
>>> arr = arr.dup;
>>> // use copy of j
>>> foreach(inout c; arr[i..$])
>>> if(' ' == c) c = '_';
>>> }
>>> </code>
>>>
>>> In this case it would be nice to be able to use a variable in the outer
>>> scope as the index in the foreach, e.i.
>>>
>>> <code>
>>> int i
>>> char[] arr;
>>>
>>> foreach(int i, c; arr)
>>> if(' ' == c)
>>> break;
>>>
>>> // i keeps the value from the last time through
>>> ...
>>> </code>
>>>
>>>
>>> Thoughts comments??
>> Wouldn't a function return serve a similar if not identical purpose?
>
> Requiring you to put the foreach in a function? Probably.
>
It just seems to me that if you want something to loop over a set and inform 
you of the stopping point, that's the natural place for a function, though I 
could be overlooking some corner cases.
> At the very least we need some way to indicate we want the behaviour as it 
> really shouldn't use variables external to the foreach by default. eg.
>
> int i;
> char[] arr;
>
> foreach(inout int i, c; arr) {}
>
> or
>
> foreach(inout i, c; arr) {}
>
> or something. Something/anything to indicate the 'i' in the loop is the 
> 'i' from outside the loop. Or, perhaps another block which is executed 
> with the foreach variables when the loop doesn't terminate normally:
>
> foreach(int i, c; arr) {
> }
> else {
>   //comes here if you use 'break' in foreach
>   //i, and c have the last values they had in the loop.
>   //what happens in the 'inout c' cases?
> }
>
> Regan 





More information about the Digitalmars-d mailing list