[Tutor] Text processing and functional programming?

Magnus Lyckå magnus at thinkware.se
Wed Aug 13 10:49:25 EDT 2003


At 23:12 2003-08-12 -0400, Clay Shirky wrote:
>My impression is that lambda and map/filter/reduce can often be replaced by
>list comprehensions. Is this correct?

List comprehension replaces map and filter (with lambdas) but
not reduce, so it doesn't do what reduce does, and in cases where
filter would return a string or a list, list comprehension will
still return a list.

E.g.

map(lambda x: x*x, l)    => [x*x for x in l]
filter(lambda x: x<5, l) => [x for x in l if x < 5]

The big syntactical gain comes when you would have combined map and filter:

map(lambda x: x*x, filter(lambda x: x<5, l)) => [x*x for x in l if x < 5]

Reduce is typically easiest to replace with a loop if
you want to avoid it, as in:

import operator
sum = reduce(operator.add, l)

sum = 0
for i in l: sum += i

For this particular case there is a builtin sum() function though.

aSum = sum(l)


--
Magnus Lycka (It's really Lyck&aring;), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 




More information about the Tutor mailing list