Can this be written more concisely in a functional style

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Tue Nov 18 01:38:09 CET 2003


On 17 Nov 2003 16:48:36 -0800, MetalOne wrote:
> 1)
> def f(xs):
>     for x in xs:
>         if test(x): return True
>     return False

Makes it obvious that there is a way for the iternation to end early.

> 2)
> return True in map(test,xs)

Strongly implies ("foo in list", "map()") that the entire list will be
iterated.  Any other behaviour would be unexpected to the person reading
the code.

> I know that I can do (2), but it operates on the whole list and the
> original may break out early.  I want the efficiency of (1), but the
> conciseness of (2).

I think that in seeking to make it more concise, you're also seeking to
make it less obvious.  Anything that has the semantics of "loop over the
whole list" in a single statement, isn't going to help people understand
that a common case is for the iteration to end early.  Which is probably
a good reason for it not to appear.

If you want to hide the algorithm, do so inside a helper function.  Then
you have consision in the places where you're actually using it, and
explicit semantics where the algorithm is implemented.

-- 
 \     "A cynic is a man who, when he smells flowers, looks around for |
  `\                                   a coffin."  -- Henry L. Mencken |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list