SCIP | SCIP程序解释 - 博客园
Part1 Bulding Abstraction with Procedure
本类blog主要对SICP书中的程序进行说明。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#+STARTUP: ** Example:Square Roots by Newton's Method #+BEGIN_SRC scheme #lang racket (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.000001)) (define (abs x) (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x)))) (define (square x) (* x x)) (define (sqrt x) (sqrt-iter 1 x)) #+END_SRC ** Procedures as Arguments #+BEGIN_SRC scheme #lang racket ;;Page 60 (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (inc n) (+ n 1)) (define (cube x) (* x x x)) (define (sum-cubes a b) (sum cube a inc b)) (define (identity x) x) (define (sum-integers a b) (sum identity a inc b)) (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) #+END_SRC ** Finding roots of equations by the half-interval method #+BEGIN_SRC scheme #lang racket ;;neg-point pos-point是指这个函数运行后的值是正还是负所对应的点 (define (search f neg-point pos-point) (let ((midpoint (average neg-point pos-point))) (if (close-enough? neg-point pos-point) midpoint (let ((test-value (f midpoint))) (cond ((> test-value 0) (search f neg-point midpoint)) ((< test-value 0) (search f midpoint pos-point)) (else midpoint)))))) (define (average x y) (/ (+ x y) 2)) (define (close-enough? x y) (< (abs (- x y)) 0.001)) ;;这里针对不同点位的情况进行了分类 (define (half-interval-method f a b) (let ((a-value (f a)) (b-value (f b))) (cond ((and (< a-value 0) (> b-value 0)) (search f a b)) ((and (> a-value 0) (< b-value 0)) (search f b a)) (else (error "Values are not of opposite sign" a b))))) ;;使用lambda表达式的好处就是用一个通用的表达式即可,而不需要反复不断的定义新的变量名字 ;;如果要使用新的(half-interval-method)过程,可以做如下的定义 (half-interval-method (lambda (x) (- (* x x x) (* 2 x) 3)) 1.0 2.0) #+END_SRC