foreach ... else statement

Nick Sabalausky a at a.a
Sun Jan 4 11:01:41 PST 2009


"bearophile" <bearophileHUGS at lycos.com> wrote in message 
news:gjqpt0$1lr5$1 at digitalmars.com...
> Brian:
>> any chance we could see something like pythons else statement on
>> iterative loops in D (Might be useful on regular for loops too but not as
>> much)?
>> http://docs.python.org/tutorial/controlflow.html#break-and-continue-
>> statements-and-else-clauses-on-loops
>
> It seems everyone has ignored this post, but this isn't a proposal coming 
> from a clueless alien. Such "else" has a little but true purpose, it helps 
> avoid gotos in some situations, and this in turn may help the optimizer, 
> because I think gotos aren't much well digested by modern C/D compilers.
>
> More on the topic:
> http://leonardo-m.livejournal.com/2008/08/07/
>
> Bye,
> bearophile

I had never heard of that before, but it certainly seems like something I'd 
find useful. Any time I'm using for or foreach to find something, I end up 
having to use some sort of "isFound" flag and check that after the loop. A 
for...else would be much nicer, for example:

bool isFound=false;
foreach(char[] key, Foo f; fooAA)
{
    if(f.someFlag && key in barAA && f.someVal > barAA[key].someVal)
    {
        isFound = true;
        break;
    }
}
if(!isFound)
    Stdout.formatln("Missing!");

// vs:

foreach(char[] key, Foo f; fooAA)
{
    if(f.someFlag && key in barAA && f.someVal > barAA[key].someVal)
        break; // found
}
else
    Stdout.formatln("Missing!");

This could also be good in conjunction with a couple things that have been 
discussed for the future of D:

- Non-nullable references:
In the above example, if I wanted to introduce a "Foo theFoo" to hold the 
Foo that was found, I could normally eliminate the "isFound" flag, and just 
encode that information into theFoo as null vs. non-null. But this means 
that there would be no excess variable that could be eliminated by using 
for..else (in fact, the *only* change made by using for...else in this case 
would be "if(!theFoo)" -> "else"). This would make it seem like for...else 
would be useless in his case, but what if we had non-nullables and you 
wanted theFoo to be non-nullable? Then you'd have to either reintroduce the 
"isFound" flag or make theFoo nullable...or use "for...else".

- Increased emphasis on functional programming:
Eliminating that "isFound" means one less bit (pardon the pun) of mutable 
state.

Granted, it's a very small improvement in any case, and there are certainly 
plenty of features that would make a far bigger difference, but this would 
still be nice to have. 





More information about the Digitalmars-d mailing list