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
(define (make-mobile left right) (list left right))
A branch is constructed from a
(which must be a number) together with a
, 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
, which return the branches of a mobile, and
, which return the components of a branch.
b. Using your selectors, define a procedure
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?
There are no comments yet.
You must log in to post a comment.Login
(define nested-left-branch (make-branch 4 5)) (define nested-right-branch (make-branch nested-left-branch (make-branch 6 7))) (define left (make-branch 1 2)) (define right (make-branch 3 nested-right-branch)) (define mobile (make-mobile left right)) (define mobile2 (make-mobile (make-branch 5 2) (make-branch 1 10))) (check-equal? (total-weight mobile) 14) (check-equal? (total-weight mobile2) 12) (check-equal? (left-branch mobile) left) (check-equal? (right-branch mobile) right) (check-equal? (branch-length left) 1) (check-equal? (branch-structure right) '((4 5) (6 7))) (check-equal? (mobile-balanced? mobile) #f) (check-equal? (mobile-balanced? mobile2) #t)