iterative lambda construction

Paul Rubin http
Mon Feb 21 16:14:00 EST 2005


"markscottwright" <markscottwright at gmail.com> writes:
> But when I try to do it iteratively, it just hangs when I try to
> evaluate the results (for count > 1):
> 
> def repeated2(f, count):
>     newfun = f
>     for i in range(count-1):
>         newfun = lambda x: newfun(f(x))
>     return newfun
> 
> For the life of me, I can't figure out why.  It seems like for count =
> 2, for example, the results from repeated2 should be lambda x: f(f(x)),
> but it doesn't seem to be.

It's Python's scoping madness.  Try:

  def repeated2(f, count):
     newfun = lambda x: x   # identity
     for i in range(count):
         newfun = lambda x, g=newfun: g(f(x))
     return newfun



More information about the Python-list mailing list