【SICP练习】27 练习1.33
来源:互联网 发布:windows 10关闭快捷键 编辑:程序博客网 时间:2024/06/01 09:55
练习1.33
题目第二行描述,只组合起由给定范围得到的项里的那些满足特定条件的项,因此我们需要在这一版本的accumulate中添加一个need-filter?,这个新的谓词可以用来传递下面就要用到的prime?。
(define (filtered-accumulateneed-filter? combiner null-value term a next b)
(if (> a b)
null-value
(let ((other-term (filtered-accumulateneed-filter?
combiner
null-value
term
(nexta)
b)))
(if (need-filter? a)
other-term
(combiner (term a) other-term)))))
因此我们就可以通过accumulate来构造一个求a到b之间所有素数的和了。就像上一道题中将accumulate补充称product等一样,这里也是将抽象的filtered-accumulate添加一些固定的元素让它稍微”具体“点。a小题的函数也就出来了。
(define(accumulate-prime-sum a b)
(filtered-accumulate prime? + 0 (lambda (x)x) a (lambda (x) (+ x 1)) b))
编译这段函数的前提是你已经将prime?加载上来了。
其实解答b小题就是要写出一个能够判断互素的谓词,这里定为a-prime-to-b?。
(define (a-prime-to-b? a b)
(and (< a b) (= 1 (gcd a b))))
同样的,在这里也应该要将gcd函数加载上来。
类似于前面将need-to-filter?替换成prime?的过程,这里是用的谓词a-prime-to-b?。
(define (product-of –prime-accumulaten)
(filtered-accumulate (lambda (x) (a-prime-to-b?x n))
*
1
(lambda (x) x)
1
(lambda (x) (+ x 1))
n))
作为初学者,还是多做点实践好了,再来写出迭代版本的filtered-accumulate
我就不再将我对比的过程写下来了,大家可以翻到前面看看。
(define (filtered-accumulateneed-to-filter? combiner null-value term a next b)
(define (filtered-accumulate-iter a other)
(cond ((> a b) other)
((need-to-filter? a)
(filtered-accumulate-iter (nexta) (combiner (term a) other)))
(else
(filtered-accumulate-iter (nexta) other))))
(filtered-accumulate a null-value))
这道题我们就这样写完了,接下来我们会开始着重学习lambda了。虽然前面用过不少,但要想灵活运用lambda则比较难了。个人理解,lambda就像是C语言中的指针,灵活运用则威力强大。
- 【SICP练习】27 练习1.33
- 【SICP练习】2 练习1.6
- 【SICP练习】3 练习1.7
- 【SICP练习】4 练习1.8
- 【SICP练习】5 练习1.9
- 【SICP练习】6 练习1.10
- 【SICP练习】7 练习1.11
- 【SICP练习】8 练习1.12
- 【SICP练习】9 练习1.15
- 【SICP练习】10 练习1.16
- 【SICP练习】11 练习1.17
- 【SICP练习】12 练习1.18
- 【SICP练习】13 练习1.19
- 【SICP练习】14 练习1.20
- 【SICP练习】15 练习1.21
- 【SICP练习】16 练习1.22
- 【SICP练习】17 练习1.23
- 【SICP练习】18 练习1.24
- 拾起过去
- Andrew Stankevich's Contest 23
- java 面试 概念点整理
- 【SICP练习】26 练习1.32
- Unity导入NGUI,新建一个Unity项目
- 【SICP练习】27 练习1.33
- C ++ 函数后面加throw()的作用
- TTS什么意思,缩写,微软TTS语音引擎(中文)5.1 “TTS”是“文本到语音(Text To Sound)”的简称
- oracle vm centos连网设置
- 程序设计中的计算复用(Computational Reuse)
- 第一篇博客
- insert时能否重用delete后的空间
- 数字证书在java中的使用
- UML序列图总结