-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.29.scm
49 lines (42 loc) · 1.21 KB
/
2.29.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(define (make-mobile left right)
(list left right))
;; @structure is either weight or mobile
(define (make-branch len structure)
(list len structure))
;; (a)
(define left-branch car)
(define right-branch cadr)
(define branch-length car)
(define branch-structure cadr)
;; (b)
(define (branch-weight branch)
(let ((structure (branch-structure branch)))
(if (pair? structure)
(total-weight structure)
structure)))
(define (total-weight mobile)
(+ (branch-weight (left-branch mobile))
(branch-weight (right-branch mobile))))
;; (c)
(define (branch-balanced? branch)
(let ((structure (branch-structure branch)))
(if (pair? structure)
(balanced? structure)
true)))
(define (balanced? mobile)
(let ((l (left-branch mobile))
(r (right-branch mobile)))
(and (branch-balanced? l)
(branch-balanced? r)
(= (* (branch-length l) (branch-weight l))
(* (branch-length r) (branch-weight r))))))
;; (d)
;; That's easy
;; Test code
(define object
(make-mobile (make-branch 0.5 22.0)
(make-branch 1
(make-mobile (make-branch 6 5)
(make-branch 5 6)))))
(total-weight object)
(balanced? object)