user3449003
user3449003

Reputation: 3

Recursive procedure that repeatedly applies any procedure a number of times

(define (repeated proc n)
  (if (= n 0)
      (lambda (x) x)
      (lambda (x)
        (proc 
         ((repeated proc (- n 1)) x)))))

I am having some trouble understanding how this procedure returns a procedure that takes a single argument and recursively applies proc to it n times.

If n = 2, is this the procedure that is returned ?

(lambda (x) (proc (((lambda (x) (proc (((lambda (x) x)) x)))) x)))

How do we evaluate this?

Upvotes: 0

Views: 44

Answers (1)

uselpa
uselpa

Reputation: 18917

This is what's happening

   (repeated proc 2)
-> (lambda (x) (proc ((repeated proc 1)                         x)))
-> (lambda (x) (proc ((lambda (x) (proc ((repeated proc 0) x))) x)))
-> (lambda (x) (proc ((lambda (x) (proc ((lambda (x) x)    x))) x)))

not

   (lambda (x) (proc (((lambda (x) (proc (((lambda (x) x)) x)))) x)))

Testing

(define (R2 proc) (lambda (x) (proc ((lambda (x) (proc ((lambda (x) x) x))) x))))
((R2 add1) 5)
=> 7

Upvotes: 2

Related Questions