Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python. I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times. For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
if count == 1:
return f
return lambda x: f(repeated(f, count - 1)(x)

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.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 4 | next ›
Discussion Overview
grouppython-list @
postedFeb 21, '05 at 8:46p
activeFeb 21, '05 at 9:33p



site design / logo © 2022 Grokbase