简体   繁体   中英

Intermediate recursive function value in Scheme

Suppose we want to implement the following recursive function in Scheme:

f(n) = f(n-1) + 1/f(n-1) [n>0] f(n) = 1 [n=0]

A simple way to this is by something like this:

(define (fn) (if (zero? n) 1 (+ (f (- n 1)) (/ 1 (f (- n 1))))))

But, as (f (- n 1)) subexpression is repeated, this code is not that much elegant. Is there any way to improve this code by binding a name to this intermediate value?

Note that a let construct can't be used here, as theoretically this causes the function to recurse forever. Practically it causes an Scheme error.

UPDATE :

Here is my code with let:

(define (afunc s n)
    (if (> n 0)
        (* .5
            (let ((next (afunc s (- n 1)))
                (+ next (/ s next))))
                s)))

It breaks with an Ill-formed special form: (let (... ...)) error.

You are on the right track, let does not impose a problem, the following works as expected.

(define (f n)
  (if (zero? n)
      1
      (let ((next (f (- n 1))))
        (+ next (/ 1 next)))))

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