简体   繁体   中英

Scheme tail-recursion/iteration

I've built a recursive function in scheme, which will repeat a given function f, n times on some input.

(define (recursive-repeated f n)
  (cond ((zero? n) identity)
        ((= n 1) f)
        (else (compose f (recursive-repeated f (- n 1))))))

I need to build an iterative version of this function with tail recursion, which I think I've done right if I understand tail recursion correctly.

(define (iter-repeated f n)
  (define (iter count total)
    (if (= count 0)
        total
        (iter (- count 1) (compose f total))))
  (iter n identity))

My question is, is this actually iterative? I believe I have it built correctly using tail recursion, but it's still technically deferring a bunch of operations until count = 0, where it executes however many compositions it's stacked up.

You pose a good question. You went from a recursive process ( recursive-repeated ) which builds a recursive process ( (f (f (f ...))) ) to an iterative process ( iter-repeated ) that builds the same recursive process.

You're right in thinking that you've basically done the same thing because the end result is the same. You just constructed the same chain in two different ways. This is the "consequence" of using compose in your implementation.

Consider this approach

(define (repeat n f)
  (λ (x)
    (define (iter n x)
      (if (zero? n)
          x
          (iter (- n 1) (f x))))
    (iter n x)))

Here, instead of building up an entire chain of function calls ahead of time, we'll return a single lambda that waits for the input argument. When the input argument is specified, we will loop inside the lambda in an iterative way for n times.

Let's see it work

(define (add1 x) (+ x 1))

;; apply add1 5 times to 3
(print ((repeat 5 add1) 3)) ;; → 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM