注:
1. DrRacket下编写;
2. 未使用块结构,主要是为了看起来更简洁;
3. 如有更优写法,欢迎批评指正;
1.3 返回三个数中较大的两个数的和
(define (sum-bigest-two x y z)
(cond ((and (< x y) (< x z)) (+ y z))
((and (< y x) (< y z)) (+ x z))
((and (< z x) (< z y)) (+ x y))))
1.7 以两次迭代guess的改变情况作为监测值实现开平方运算。(选定精确度为0.000001)
(define (sqrt-iter-s guess last x)
(if (good-enough? guess last)
guess
(sqrt-iter-s (improve guess x) guess x)))
(define (good-enough? now last)
(< (abs (- last now)) 0.000001))
(define (abs x)
(cond((< x 0) (- x))
((= x 0) 0)
((> x 0) x)))
(define (improve guess x)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
(define (sqrt-s x)
(sqrt-iter-s 1.0 0 x))
1.8 实现立方根运算(由上述1.7的代码修改计算公式而来)
(define (cbrt-iter guess last x)
(if (good-enough? guess last)
guess
(cbrt-iter (improve guess x) guess x)))
(define (good-enough? now last)
(< (abs (- last now)) 0.000001))
(define (abs x)
(cond((< x 0) (- x))
((= x 0) 0)
((> x 0) x)))
(define (improve guess x)
(third (/ x (square guess)) (* 2 guess)))
(define (third x y)
(/ (+ x y) 3))
(define (square x) (* x x))
(define (cbrt x)
(cbrt-iter 1.0 0 x))
1.11
(1) 递归计算过程
(define (f-recu n)
(if (< n 3)
n
(deal (f-recu (- n 1)) (f-recu(- n 2)) (f-recu(- n 3)))))
(define (deal x y z)
(+ (* 1 x)
(* 2 y)
(* 3 z)))
(2) 迭代计算过程
(define (f n)
(f-iter 0 1 2 n))
(define (f-iter a b c count)
(if (< count 3)
c
(f-iter b c (improve a b c) (- count 1))))
(define (improve x y z)
(+ (* 3 x)
(* 2 y)
(* 1 z)))
注意递归和迭代变量乘的顺序是恰好相反的,即123和321;
1.12
row表示行数,number表示该行的第几个数;
例如,(pascal 5 3)表示求第五行第三个数,结果为6;
(define (pascal row number)
(if (or (= number 1)
(= row number)
(= row 2))
1
(+ (pascal (- row 1) (- number 1))
(pascal (- row 1) number))))