[FP] Rewriting name bindings as expressions

Richard Davies richardd at pobox.com
Thu May 24 10:46:55 EDT 2001


I've been reading David Mertz's excellent "Charming Python" articles
at developerWorks on functional-style programming, in which, amongst
other things, he shows how to rewrite some common types of statements
as expressions. Continuing this idea, I'm after a good clean way of
rewriting name bindings as expressions.

To take an example, consider:

ans = []
for x in range(10):
   y = x*x
   ans.append(y+1)

We can rewrite this as a list comprehension:

ans = [x*x+1 for x in range(10)]

but, given that the list comprehension starts with an expression,
not a block of statements, how do we do so whilst binding y to x*x
part way through (of course both x*x and y+1 are much more
complicated in general).

I've come up with either:

y = lambda x: x*x
ans = [y(x)+1 for x in range(10)]

which isn't really satisfactory since y becomes a function and
also ends up defined outside (i.e. not in the expression)

or:

ans = [(lambda y: y+1)(y=x*x) for x in range(10)]

with the disadvantage that you must type each name binding twice
(or rely on order, textually separating the names from the things
which they're bound to)

or:

ans = [(lambda **vars: vars['y']+1)(y=x*x) for x in range(10)]

with each name binding once in a single place, but very
awkward syntax.


Can anyone provide better suggestions? I'm aiming for something
like ML's

let y=x*x in y+1

which is a single expression!


Thanks,

Richard.



More information about the Python-list mailing list