foreach ... else statement

Daniel de Kok me at nowhere.nospam
Sun Jan 4 13:23:14 PST 2009


On Sun, 04 Jan 2009 14:01:41 -0500, Nick Sabalausky wrote:
> 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!");
[...]
> - Increased emphasis on functional programming: Eliminating that
> "isFound" means one less bit (pardon the pun) of mutable state.

It's a common pattern indeed, but I am not sure if this is the prettiest 
solution. The slightly awkward idiom in the first example is needed 
because a for loop is not a function you can return from. Wouldn't it be 
more adequate to rewrite this as a function/method that takes a predicate?

if (range.exists(predicate)) {}

or

if (exists(range, predicate) {}

-- Daniel



More information about the Digitalmars-d mailing list