Can this be written more concisely in a functional style

Jeremy Fincher tweedgeezer at hotmail.com
Tue Nov 18 22:04:33 CET 2003


mis6 at pitt.edu (Michele Simionato) wrote in message news:<2259b0e2.0311180714.4f605bab at posting.google.com>...
> tweedgeezer at hotmail.com (Jeremy Fincher) wrote in message news:<698f09f8.0311180259.bdd4359 at posting.google.com>...
> > def any(p, seq):
> >     """Returns true if any element in seq satisfies predicate p."""
> >     for elt in itertools.ifilter(p, seq):
> >         return True
> >     else:
> >         return False
> > 
> > def all(p, seq):
> >     """Returns true if all elements in seq satisfy predicate p."""
> >     for elt in itertools.ifilterfalse(p, seq):
> >         return False
> >     else:
> >         return True
> 
> This is a perfect example of why I dislike the "else" clause. I
> would code this as 
> 
> def any(p, seq):
>     """Returns true if any element in seq satisfies predicate p."""
>     for elt in itertools.ifilter(p, seq):
>         return True
>      return False
> 
> def all(p, seq):
>     """Returns true if all elements in seq satisfy predicate p."""
>     for elt in itertools.ifilterfalse(p, seq):
>         return False
>      return True
> 
> Since the "else" is unnecessary, it disturbs me, I get confused,
> I don't see why it is used (there is no break in the loop)

It's used because the for loop is effectively serving as an if
statement.  Iterators have no __nonzero__ method -- you can't simply
bool() them.  So I use a for loop like a if statement, and throw the
else in there to emphasize that usage.  The for loop will never
iterate; either its body executes or it doesn't.

An alternative way to code this would be:

def any(p, seq):
    try:
        itertools.ifilter(p, seq).next()
        return True
    except StopIteration:
        return False
    
but I find that less clear.

I also use else because it puts my return statements at the same level
of indentation, which I find more readable, since logically they're
equivalent.

> Am I the only one? ;)

One can only hope! <wink>

Jeremy




More information about the Python-list mailing list