Re: Can this be written more concisely in a functional style

From: Ben Finney (bignose-hates-spam_at_and-benfinney-does-too.id.au)
Date: 11/18/03


Date: 18 Nov 2003 11:28:09 +1050

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/>


Relevant Pages

  • Estimating the condition of an upper triangular matrix
    ... algorithm to estimate the condition (i.e. the ratio of the largest and ...
    (sci.math.num-analysis)
  • Re: How to take in a string of any size?
    ... On Mon, 23 Aug 2004, josh wrote: ... >> There's a minor benefit of that it makes the algorithm Oinstead ... > Counting and seeking back to the start would be O(even if seeking itself ...
    (comp.lang.c)
  • Re: Essay on PID Motor control
    ... I still did not get the basic information I'm seeking, to wit: ... > 1) Is the algorithm as published not the same as the one tested? ...
    (comp.robotics.misc)
  • Re: main connective in SL
    ... Enderton) wrote: ... >> what's the main connective in these two logic strings, ... > Perhaps you are seeking an algorithm that counts the left and ...
    (sci.logic)