我们可以通过定义一个通用的sum来进行求和.传入过程作为参数
练习1.29,利用辛普森法则进行积分求和,需要注意的一点是闭包的性质,在integral里面的参数都是可以直接用在里面的闭包里面的.
(define (sum f a next b)
( if(> a b)
0
(+ (f a) (sum f (next a) next b))
)
)
(define (cube x) (* x x x))
(define (integral f a b n)
(define h (/ (- b a) n))
(define (simp_next k) (+ k 1))
(define (factor k)
(cond ((or (= k 0) (= k n)) 1)
((odd? k) 4)
(else 2)))
(define (term k) (* (factor k) (f (+ a (* k h)))))
(if (not (even? n))
(error "n can't be odd")
(* (/ h 3)
(sum term 0.0 simp_next n)))
)
1.30,将sum改成迭代执行的形式:
(define (sum term a next b)
(define (iter a result)
( if(> a b)
result
(iter (next a) (+ result (term a)))))
( iter a 0);sum body
)
1.31定义Product,并且用product定义Factorial,然后利用Product计算PI:
(define (square a)( * a a))
(define (product f a next b)
(define (iter a result)
( if (> a b)
result
(iter (next a) (* (f a) result))))
(iter a 1);function body
);end
(define (factorial n)
(product (lambda(x) x)
1
(lambda(x)(+ x 1))
n)
)
(define (PI n)
(define (term k) (square(/ (+ k 1) k)));(k+1/k)^2
(define factor (/ 8 (+ n 1)));8/(n+1)
(* factor
(product term
3.0
(lambda (x)(+ x 2))
n);function body
))
对于pi的序列我将它们写成(k+1)/(k)的形式进行计算,再去掉多乘上的系数即可.
1.32定义accumulate
;定义accumulate
(define (accumulate combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (term a) result))
)
)
(iter a null-value)
)
练习1.33
(a)
;定义filered_accumulate
(define (accumulate combiner null-value term a next b Satisfy?)
(define (iter a result)
(cond ((> a b)
result)
((Satisfy? a)
(iter (next a) (combiner (term a) result))
)
(else
(iter (next a) result)
)
)
)
(iter a null-value)
)
(define (sum_primes a b)
(accumulate + 0 (lambda(x) x) a (lambda(x) (+ x 1)) b prime?)
)
(b)求解所有小于n且与n互素的正整数之积.
(define (f a b)
( if ( = b 0) ;a%b == 0
a
(f b (remainder a b));a<-b,b = a%b
)
)
(define (sum_gcd n)
(define (GCD? x) (=(f n x) 1))
(accumulate * 1 (lambda(x) x) 1 (lambda(x) (+ x 1)) n GCD?)
)
练习1.34,这个题我个人有两种理解方式:
(ff)=>(f2)=>(22)=>2不是函数,出错
第二种理解方式
(f f)=>
(f (lambda (g)
(g 2)))=>
((lambda (g)
(g 2))
(lambda (g)
(g 2)))=>
((lambda (g)
(g 2))
2)=>
(2 2)