Sunday, June 7, 2009

Ex-2.29

;a
(define (left-branch m)
(car m))
(define (right-branch m)
(cadr m))
(define (branch-length b)
(car b))
(define (branch-structure b)
(cadr b))

;b
;total weight of a mobile
(define (total-weight m)
(+ (branch-total-weight (left-branch m))
(branch-total-weight (right-branch m))))


;find total weight of a branch
(define (branch-total-weight b)
(if (pair? (branch-structure b))
(total-weight (branch-structure b))
(branch-structure b)))

;test
(define b1 (make-branch 1 2))
(define b2 (make-branch 1 3))
(define m1 (make-mobile b1 b2))
(define b3 (make-branch 1 5))
(define b4 (make-branch 1 m1))
(define m (make-mobile b3 b4))
(total-weight m)
;Value: 10

;c
(define (balanced? m)
(let ((lb (left-branch m))
(rb (right-branch m)))
(and
(branch-balanced? lb)
(branch-balanced? rb)
(=
(* (branch-length lb) (branch-total-weight lb))
(* (branch-length rb) (branch-total-weight rb))))))
;see if a branch has a mobile structure and its
;balanced, if it has weight then return true
(define (branch-balanced? b)
(if (pair? (branch-structure b))
(balanced? (branch-structure b))
#t))

;test
(define b1 (make-branch 1 2))
(define b2 (make-branch 1 3))
(define m1 (make-mobile b1 b2))
(define b3 (make-branch 1 5))
(define b4 (make-branch 1 m1))
(define m (make-mobile b3 b4))
(balanced? m)
;Value: #f
(define b2 (make-branch 1 2))
(define m1 (make-mobile b1 b2))
(define b4 (make-branch 1 m1))
(define m (make-mobile b4 b4))
;value: #t

;d
Since we abstracted out the details of how we select various component of mobile and branch, so only selectors need to change.
(define (left-branch m)
(car m))
(define (right-branch m)
(cdr m))
(define (branch-length b)
(car b))
(define (branch-structure b)
(cdr b))

No comments:

Post a Comment