【SICP练习】59 练习2.29
来源:互联网 发布:吊顶面积算法 编辑:程序博客网 时间:2024/06/05 23:54
练习2.29
这种题,还有之前的那个rectangle的题目,对于变量、函数等的命名简直要让人疯掉。先来写出题目中的left-branch和right-branch吧。
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(cadr mobile))
注意这里是cadr而不是cdr。对应的branch-length和branch-structure。
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(cadr branch))
a小题并不难,b小题中的total-weight也就是要求每部分branch-structure。而根据题目的意思,如果一个分支吊着另一个活动体,那么这个活动体的重量就是这个分支的重量,否则分支的structure就是这个分支的重量。而判断这个分支是不是还有其他活动体我们可以用pair?来判断。而总重量就是左右两部分的重量之和。
(define (branch-weight branch)
(if (pair? (branch-structure branch))
(total-weight (branch-weight branch))
(branch-structure branch)))
(define (total-weight mobile)
(+ (branch-weight (left-branch mobile))
(branch-weight (right-branch mobile))))
我们来测试一下结果。
(define first-mobile (make-mobile(make-branch 20 10)
(make-branch20 40)))
(total-weight mobile)
;Value: 50
(define second-mobile (make-mobile(make-branch 40 first-mobile)
(make-branch 100 180)))
;Valeu: 230
下面开始做c小题了。先来看看什么是力矩—左杆的长度乘以吊在杆上的重量,等于这个活动体右边的同样乘积。这是活动体称为平衡的第一个条件,第二个条件则是要每个分支上吊着的子活动体也都平衡。于是我们可以定义如下的过程,我们先来定义力矩好了。
(define (branch-force branch)
(* (branch-length branch)
(branch-weight branch)))
(define (mobile-balance? mobile)
(let ((left (left-branch mobile))
(right (right-branch mobile)))
(and (= (branch-force left)
(branch-force right))
(branch-balance? left)
(branch-balance? right))))
(define (branch-balance? branch)
(if (pair? (branch-structure branch))
(mobile-balance? (branch-structure branch))
#t))
c小题我们也做完了,下面我们来乘胜追击完成最后一个小题好了。d小题将原先的list改成了cons。因此一开始所说的在right-branch和branch-structure要用cadr而不能用cdr,但是在这里用cdr就是正确的了。
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(cdr mobile))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(cdr branch))
是不是感觉很神奇呢?那就来测试吧。
(define third-mobile (make-mobile(make-branch 20 25)
(make-branch30 40)))
;Value: third-mobile
third-mobile
;Value: ( ( 20 . 25) 30 . 40 )
注意第二章所讲的数据抽象,因此前面的mobile-balance?在这里也是一样可以用的。
- 【SICP练习】59 练习2.29
- 【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
- 【SICP练习】55 练习2.23
- 【SICP练习】56 练习2.24-2.26
- 【SICP练习】57 练习2.27
- 公司级项目管理例会的汇报内容
- 【SICP练习】58 练习2.28
- 【SICP练习】59 练习2.29
- ReactOS SYSCALL_PROLOG/TRAP_EPILOG及相关代码注释 (2) --ZwContinue
- 【SICP练习】60 练习2.30
- 【SICP练习】61 练习2.31-2.32
- 抓住那只喵(HTML5-神经猫)
- BZOJ1406 密码箱
- 【SICP练习】62 练习2.33
- STL for_each
- 【SICP练习】63 练习2.34