Foreach Closures?

Andrej Mitrovic andrej.mitrovich at gmail.com
Tue Apr 10 02:33:07 PDT 2012


On 4/9/12, Kevin Cox <kevincox.ca at gmail.com> wrote:
> The
> reason I aski is because if you have a return statement inside a foreach it
> returns from the outside function not the "closure".

I don't like this subtle thing. For example let's say a newbie were to
implement a function called "isDirEmpty". The first hint is to try to
walk the directory iteratively and return as soon as there's a match,
e.g.:

bool isEmptyDir(string path)
{
    foreach (_; dirEntries(path, SpanMode.shallow))
        return false;

    return true;
}

isEmptyDir never returns false. All that false statement does is break
out of the foreach loop.

Of course the right way to implement this is:

bool isEmptyDir(string path)
{
    return dirEntries(path, SpanMode.shallow).empty;
}

But still, the first version is extremely subtle. The semantics of
that code completely change based on whether dirEntries is an array, a
range, or an opApply.


More information about the Digitalmars-d mailing list