练习1.31-练习1.34
来源:互联网 发布:传奇人物数据保存失败 编辑:程序博客网 时间:2024/05/20 03:40
最近对于Lisp的强大和高深还是深有体会的,可以将函数作为参数进行调用,这样在很大的程度上可以提高函数的抽象性,即将具有公共模式的函数进行抽象。例如在SICP中,首先将累加和的过程进行了抽象,然后在累加和的基础上抽象出了累乘积,进而又发现了累加和与累乘积的共同点,进一步抽象成了一个叫做accumulate的函数,这个函数的是这样的
(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)
(define (product-recur term a next b) (if (> a b) 1 (* (term a) (product-recur term (next a) next b))))
(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)))
(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)
(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.32
a)
(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))))
(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)
(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
(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)
(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)
(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上的所有题,貌似很久没有更新了,但以后做了题还是可以和这个上面已有的解答对对了。
0 0
- 练习1.31-练习1.34
- 练习
- “++”“--”练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- 练习
- linux常用命令大全
- 纯C读取24位图并且绘画在桌面
- zoj 1143 && poj 1044 Date bugs ------模拟!
- tomcat启动一直报空指针错误
- Why CCP is still using Python 2
- 练习1.31-练习1.34
- swap分区扩展
- libiberty required to compile MemProf
- ./startup.sh: /bin/sh^M: bad interpreter: 没有那个文件或目录 解决办法
- 倍增lca模板
- 怎样从oracle导入备份的数据
- Android中的JSON详细总结
- JBoss 系列八十四: 使用 JMS session 时的一个误区
- 如何面试有多年工作经验的高级程序员