先看看SICP Exercise 1.11
Exercise 1.11. 写道
A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n -
3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that
computes f by means of an iterative process.
3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that
computes f by means of an iterative process.
这里定义了一个函数f(n), 他满足以下规则:
f(n) = n if n < 3
f(n) = f(n-1) + 2 * f(n-2) + 3 * f(n-3)
需要分别使用递归和迭代的方法来编写函数计算f(n)的结果。
递归的方法,显然是最简单的:
(defun calc-f (n)
(if (< n 3)
n
(+ (calc-f (- n 1))
(* (calc-f (- n 2)) 2)
(* (calc-f (- n 3)) 3)
))
)
迭代的方法我们应该怎么写呢?先看一下sicp中介绍的关于Fibonacci的介绍:
(define (fib n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (fib (- n 1))
(fib (- n 2))))))
如果使用一两个数值a 和b,那整个计算的过程是下面两步的迭代:
写道
a ← a + b
b ← a
b ← a
所以,使用迭代的方法来计算Fibonacci数列,可以用下面的方法:
(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
其中,引入了一个方法 fib-iter, 它增加了a、b两个参数,不停的按照上面的规则来迭代直到找到我们想要的结果。
如果按照前面的规则来计算f(n),那我们需要三个变量a b c,然后重复执行下面的规则
写道
a ← a + 2b + 3c
c ← b
b ← a
c ← b
b ← a
照葫芦画瓢,下面是计算f的迭代写法:
(defun calc-f (n)
(calc-f-iter 2 1 0 n)
)
(defun calc-f-iter (a b c count)
(if (= count 0)
c
(calc-f-iter (+ a (* b 2) (* c 3))
a
b
(- count 1))))
SICP习题1.11解析
本文解析了SICP习题1.11中的函数f(n),介绍了如何通过递归和迭代两种方式实现该函数。递归方法简洁明了,而迭代方法则需借助三个变量进行迭代计算。
175

被折叠的 条评论
为什么被折叠?



