Based on your previous question, you're going about it in a totally imperative way (and incorrect, of course, otherwise you wouldn't be asking this question), which is not how Scheme likes to work. Here's a functional (but not iterative) way to write the function:
(define (f n)
(if (< n 4)
n
(+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3))) (* 4 (f (- n 4))))))
Now, let's see how one might write this iteratively. First, let's see how an iterative Fibonacci function is written:
(define (fib n)
(let loop ((i 0) (a 0) (b 1))
(if (>= i n)
a
(loop (+ i 1) b (+ a b)))))
This does the same thing as the following JavaScript:
fib = function (n) {
return (function loop(i, a, b) {
return i >= n ? a : loop(i + 1, b, a + b);
})(0, 0, 1);
};
Notice how i
, a
, and b
actually get updated. We use tail-recursion to update the values, not by reassignment/mutation (i.e., not using =
in JS or set!
in Scheme). I recently wrote an answer about why tail-recursion is so important in Scheme.
So, you would do something similar with your function:
(define (f n)
(let loop ((i 0) (a 0) (b 1) (c 2) (d 3))
(if (>= i n)
a
(loop (+ i 1) b c d (+ d c c b b b a a a a)))))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…