Exercise 1.3. Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
求三个数中最大两个数字的平方和,我们可以直接比较:
(define (sum-of-square-of-largest-two-1 x y z)
(cond ((and (> x y) (> y z))
(+ (* x x) (* y y)))
((and (> x y))
(+ (* x x) (* z z)))
((> x z) ; and also (< x y)
(+ (* x x) (* y y)))
(else
(+ (* z z) (* y y)))))
然后对三个数进行 6 种不同顺序的测试:
(load "../testframe.scm")
(assert= (sum-of-square-of-largest-two-1 2 3 4) 25)
(assert= (sum-of-square-of-largest-two-1 2 4 3) 25)
(assert= (sum-of-square-of-largest-two-1 3 2 4) 25)
(assert= (sum-of-square-of-largest-two-1 3 4 2) 25)
(assert= (sum-of-square-of-largest-two-1 4 2 3) 25)
(assert= (sum-of-square-of-largest-two-1 4 3 2) 25)
这个过程的确满足我们的要求,但我们把所有的操作全部放到一个过程中,这使得我们如果要修改过程的某一部分就会比较困难,比如:
- 求 3 个数最大的两个数的三次方和
- 求 4 个数中最大的两个数的平方和
这些问题都是有共同的地方的,我们如何把这些共同的地方全部提取出来单独形成过程就产生了 SICP 第二章的内容。