M
markscottwright
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
else:
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.
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
else:
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.