[FP] Rewriting name bindings as expressions

Richard Davies richardd at pobox.com
Fri May 25 08:37:45 EDT 2001


Greg Ewing wrote:
> Richard Davies wrote:
> > 
> > ans = []
> > for x in range(10):
> >    y = x*x
> >    ans.append(y+1)
> > 
> > We can rewrite this as a list comprehension
> > but ... how do we do so whilst binding y to x*x
> 
> ans = [y+1 for x in range(10) for y in (x*x,)]

This certainly solves the stated problem brilliantly,
but isn't so good in the general case of rewriting
name bindings as expressions when there aren't any
lists involved.

For instance, the ML

z = let y = x+1 in y+y*y

becomes

z = [y+y*y for y in x+1,][0]

which is good, but could be nicer if we never had to
bring lists into it...

Richard.



More information about the Python-list mailing list