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 left 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 off its 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?

 

(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 ((= (branch-length (left-branch mobile)) 1) (+ (branch-structure (left-branch mobile)) (total-weight (right-branch mobile))))
        ((= (branch-length (right-branch mobile)) 1) (+ (branch-structure (right-branch mobile)) (total-weight (left-branch mobile))))
        (else (+ (total-weight (left-branch mobile)) (total-weight (right-branch mobile))))))
 

(c)

 

(define (is-balanced? mobile)
  (let ((left (left-branch mobile))
        (right (right-branch mobile)))
    (= (* (branch-length (left mobile)) (total-weight (left mobile)))
    (* (branch-length (right mobile)) (total-weight (right mobile))))))

 

(d)

 

简单的使用cdr即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值