练习1.31-练习1.34

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2014/01/10/2014-01-10-练习1.31-练习1.34/

访问原文「练习1.31-练习1.34

最近对于Lisp的强大和高深还是深有体会的,可以将函数作为参数进行调用,这样在很大的程度上可以提高函数的抽象性,即将具有公共模式的函数进行抽象。例如在SICP中,首先将累加和的过程进行了抽象,然后在累加和的基础上抽象出了累乘积,进而又发现了累加和与累乘积的共同点,进一步抽象成了一个叫做accumulate的函数,这个函数的是这样的

1
(accumulate combiner null-value term a next b)

其中combiner为被组合项的组合方式,例如在累加和中可以是“+”,在累乘积中可以是“*”,null-value为默认值,在累加和中为0累乘积中为1,term为函数f,例如在求cube的积分时,f为cube,a为初始值,next为下一次取得值,b为取值的上限。最后在accumulate函数的基础上加上了对数据的filter使得整个过程更加抽象更加一般。
1.练习1.31
a)

1
2
3
4
5
(define (product-recur term a next b)
(if (> a b)
1
(* (term a)
(product-recur term (next a) next b))))
1
2
3
4
5
6
7
8
(define (factorial-recur n)
(define (self n)
n)
(define (plus-1 n)
(+ n 1))
(if (= n 0)
1
(product-recur self 1 plus-1 n)))
1
2
3
4
5
6
7
8
9
10
11
(define (pi-recur n)
(define (even? n)
(= (remainder n 2) 0))
(define (item n)
(if (even? n)
(/ (+ 2 n) (+ 1 n))
(/ (+ 1 n) (+ 2 n))))
(define (next-1 n)
(+ n 1.0))
(* 4.0
(product-recur item 1.0 next-1 n)))

b)

1
2
3
4
5
6
(define (product-iter term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* (term a) result))))
(iter a 1))

2.练习1.32a)

1
2
3
4
5
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
1
2
3
4
5
(define (sum-accumulate term a next b)
(accumulate + 0 term a next b))
(define (product-accumulate term a next b)
(accumulate-iter * 1 term a next b))

b)

1
2
3
4
5
6
(define (accumulate-iter combiner null-value term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner result (term a)))))
(iter a null-value))

3.练习1.33

1
2
3
4
5
6
(define (filtered-accumulate filter combiner null-value term a next b)
(define (iter a result)
(cond ((> a b) result)
((filter a) (iter (next a) (combiner (term a) result)))
(else (iter (next a) result))))
(iter a null-value))

a)

1
2
3
4
5
6
(define (prime-sum a b)
(define (next-1 a)
(+ a 1))
(define (self a)
a)
(filtered-accumulate prime? + 0 self a next-1 b))

b)

1
2
3
4
5
6
7
8
(define (GCD-1-product n)
(define (GCD-1-n? a)
(= (GCD a n) 1))
(define (next-1 a)
(+ a 1))
(define (self a)
a)
(filtered-accumulate GCD-1-n? * 1 self 1 next-1 (- n 1)))

4.练习1.34可以这么解释(f f)->(f 2)->(2 2),最后由于2这个函数没有定义,所以报错结束。

网上发现了这个点击打开链接,很不错,貌似是一些人做的项目,目的是解答SICP上的所有题,貌似很久没有更新了,但以后做了题还是可以和这个上面已有的解答对对了。

Jerky Lu wechat
欢迎加入微信公众号