map/filter/reduce/lambda opinions and background unscientificmini-survey

Christopher Subich spam.csubich+block at block.subich.spam.com
Sun Jul 3 13:57:19 EDT 2005


Carl Banks wrote:

> Listcomps et al. cannot do everything map, lambda, filter, and reduce
> did.  Listcomps are inferior for functional programming.  But, you see,
> functional is not the point.  Streamlining procedural programs is the
> point, and I'd say listcomps do that far better, and without all the
> baroque syntax (from the procedural point of view).

I've heard this said a couple times now -- how can listcomps not 
completely replace map and filter?

I'd think that:
mapped = [f(i) for i in seq]
filtered = [i for i in seq if f(i)]

The only map case that doesn't cleanly reduce is for multiple sequences 
of different length -- map will extend to the longest one (padding the 
others with None), while zip (izip) truncates sequences at the shortest. 
  This suggests an extension to (i)zip, possibly (i)lzip ['longest zip'] 
that does None padding in the same way that map does.

Reduce can be rewritten easily (if an initial value is supplied) as a 
for loop:
_accum = initial
for j in seq: _accum=f(_accum,j)
result = _accum

(two lines if the result variable can also be used as the accumulator -- 
this would be undesirable of assigning to that can trigger, say, a 
property function call)

Lambdas, I agree, can't be replaced easily, and they're the feature I'd 
probably be least happy to see go, even though I haven't used them very 
much.



More information about the Python-list mailing list