問題 2.29

  • これからは問題ごとに記事にする
    • 以前のものもそう直す。
(define (make-mobile left right)
  (list left right))

(define (make-branch length structure)
  (list length structure))

(define mobile1
  (make-mobile (make-branch 3 6) (make-branch 9 2)))
(define mobile2
  (make-mobile (make-branch 2 mobile1) (make-branch 4 4)))
(define mobile3
  (make-mobile (make-branch 4 mobile1) (make-branch 2 mobile2)))

;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 structure)
  (if (pair? structure)
      (+
       (total-weight (branch-structure (left-branch structure)))
       (total-weight (branch-structure (right-branch structure))))
      structure))

(total-weight mobile1)
;-> 8

(total-weight mobile2)
;-> 12

(total-weight mobile3)
;-> 20

;ok

;c
(define (balanced? mobile)
  (= (* (branch-length (left-branch mobile))
        (total-weight (branch-structure (left-branch mobile))))
     (* (branch-length (right-branch mobile))
        (total-weight (branch-structure (right-branch mobile))))))

(balanced? mobile1)
;-> #t

(balanced? mobile2)
;-> #t

(balanced? mobile3)
;-> #f

;ok

;d
(define (make-mobile left right)
  (cons left right))

(define (make-branch length structure)
  (cons length structure))

(define mobile1
  (make-mobile (make-branch 3 6) (make-branch 9 2)))
(define mobile2
  (make-mobile (make-branch 2 mobile1) (make-branch 4 4)))
(define mobile3
  (make-mobile (make-branch 4 mobile1) (make-branch 2 mobile2)))

;↑こうする場合、

(define (right-branch mobile) (cdr mobile))
(define (branch-structure branch) (cdr branch))

;↑こう変える必要があるのみである。

(total-weight mobile1)
;-> 8

(total-weight mobile2)
;-> 12

(total-weight mobile3)
;-> 20

(balanced? mobile1)
;-> #t

(balanced? mobile2)
;-> #t

(balanced? mobile3)
;-> #f

;ok簡単!