Can this be written more concisely in a functional style

Michele Simionato mis6 at pitt.edu
Tue Nov 18 10:14:45 EST 2003


tweedgeezer at hotmail.com (Jeremy Fincher) wrote in message news:<698f09f8.0311180259.bdd4359 at posting.google.com>...
> Anyway, here are more efficient implementations:
> 
> 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
> 
> Jeremy

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) and the
code becomes much harder to read, for me. OTOH I am sure 99% of 
people would say "look, it is obvious, if elt is in the output
of ifilter it will return True, else False (viceversa in the
second case)". But may brain sees that the "else" is unncessary
and immediately it is disturbed by th redundance.
Am I the only one? ;)

                 Michele




More information about the Python-list mailing list