[Tutor] Text processing and functional programming?

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Aug 14 23:23:17 EDT 2003


> Put another way, other than preference for different flavors of
syntactic
> sugar, would you ever prefer map/filter/lambda to list
comprehensions, or
> v-v?

Its a matter of readability. If you undertand the FP principles
map/filter etc are much more readable - they express the intent
better.

For example, we can write:

if x > 5:
    y = x
else:
    y = 2*x

or we can write

y = ((x > 5) and x) or 2*x

They mean the same, but the first is easier to understand unless
you happen to be fluent in boolean algebra.

Similarly a comprehension, precisely because it can do so many
things has to be read and studied much more carefully that an
expression using map/filter etc. The comprehension just tells
you a list is being returned, you have to read the content to
see what kind of transformation is being done.

However if you aren't already familiar with FP concepts then
comprehensions probably tell you as much as the named functions
do - and are usually faster!

> And, relatedly, are list comprehensions FP constructs,

Yes, they come from Haskell most directly but the concept of
comprehensions exists in the math too.

> > avoid the intimidating keyword "lambda", but oh well.  *grin*

But lambda is the intuitive name for anyone who has loked at the
math. If you have studied the lamda calculus any other name would
seem totally bizarre! A lambda is a lambda, thats its name. Its
like deciding to call a tuple a 'bunch' just because you hadn't
heard the term tuple used before... They are both the correct
mathematical term for the concept they embody.

> Is it just that these are examples, and at some point you want to
write a
> def that performs so many functions that you don't want to write it
in-line?

Exactly so, Danny was just keeping it short.

> Are there times when you can do something with one of those
constructs but
> not the other?

Well a lambda is completely unrelated to the others. You don't need
lambda to use map or filter and you can use lambda in writing a
comprehension. In fact, ironically, before comprehensions came along
lambda was never needed because you could allways use def instead, but
comprehensions provide (I think) the only place in Python where
lambda is the only way to do it.(You can of course build such a list
without lambdas using a loop)

What I refer to is the ability to generate a list of functions
using a comprehension:

>>> numbers = [2,5,9]
>>> multipliers = [lambda x,y=z: y*x for z in numbers]
>>> for n in range(3):
...    print multipliers[n](7)
...
14
35
63
>>>

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list