sicp每日一题[2.29]
Exercise 2.29
A binary mobile consists of two branches, a left branch and a right branch. Each branch is a rod of a certain length, from which hangs either a weight or another binary mobile. We can represent a binary mobile using compound data by constructing it from two branches (for example, using list):
(define (make-mobile left right)
(list left right))
A branch is constructed from a length (which must be a number) together with a structure, which may be either a number (representing a simple weight) or another mobile:
(define (make-branch length structure)
(list length structure))
a. Write the corresponding selectors left-branch and right-branch, which return the branches of a mobile, and branch-length and branch-structure, which return the components of a branch.
b. Using your selectors, define a procedure total-weight that returns the total weight of a mobile.
c. A mobile is said to be balanced if the torque applied by its top-left branch is equal to that applied by its top right branch (that is, if the length of the le rod multiplied by the weight hanging from that rod is equal to the corresponding product for the right side) and if each of the submobiles hanging offits branches is balanced. Design a predicate that tests whether a binary mobile is balanced.
d. Suppose we change the representation of mobiles so that the constructors are
(define (make-mobile left right) (cons left right))
(define (make-branch length structure)
(cons length structure))
How much do you need to change your programs to convert to the new representation?
这道题主要是需要理解 mobile 是什么东西,我感觉它跟杠杆很像,然后就比较好处理了。
; a
(define (left-branch mobile)
(car mobile))
(define (right-branch mobile)
(car (cdr mobile)))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(car (cdr branch)))
; b
(define (total-weight mobile)
(cond ((null? mobile) 0)
((not (pair? mobile)) mobile)
(else (+ (total-weight (branch-structure (left-branch mobile)))
(total-weight (branch-structure (right-branch mobile)))))))
; c
(define (torque branch)
(* (branch-length branch)
(total-weight (branch-structure branch))))
(define (balanced? mobile)
(if (not (pair? mobile))
true
(= (torque (left-branch mobile))
(torque (right-branch mobile)))))
(newline)
(define a (make-mobile (make-branch 2 3) (make-branch 3 2)))
(total-weight a)
(balanced? a)
(newline)
(define b (make-mobile (make-branch 2 a) (make-branch 4 a)))
(total-weight b)
(balanced? b)
(newline)
(define c (make-mobile (make-branch 2 b) (make-branch 3 a)))
(total-weight c)
(balanced? c)
; 执行结果
5
#t
10
#f
15
#f
; d
(define (right-branch mobile)
(cdr mobile))
(define (branch-structure branch)
(cdr branch))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?