问题
Is anyone familiar with this?
Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. The procedure should be able to be used as follows:
((repeated square 2) 5) 625
I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here:
(define (compose f g) (lambda (x) (f (g x))))
回答1:
Well, you probably want something like this, right?
((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))
(I don't know whether identity
is predefined in Scheme. If not, it's easy to write.)
Now, this is not directly reproducible because you can't magically enclose code outside of the call to repeated
with arbitrary stuff. However, what do these reduction steps look like when rewritten using compose
? Can you make out a pattern in the resulting list of steps and reproduce it?
回答2:
(define (repeated f n)
(if (zero? n)
identity
(lambda (x) ((repeated f (- n 1)) (f x)))))
or, if you insist on using "compose":
(define (repeated f n)
(if (zero? n)
identity
(compose (repeated f (- n 1)) f)))
来源:https://stackoverflow.com/questions/249374/scheme-procedure-to-compute-the-nth-repeated-application-of-a-function