-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.29.scm
55 lines (42 loc) · 1.46 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
50
51
52
53
54
55
; (define (make-mobile left right)
; (list left right))
; (define (make-branch length structure)
; (list length structure))
; (define (left-branch structure)
; (car structure))
; (define (right-branch structure)
; (car (cdr structure)))
; (define (branch-length branch)
; (car branch))
; (define (branch-structure branch)
; (car (cdr branch)))
(define (make-mobile left right)
(cons left right))
(define (make-branch length structure)
(cons length structure))
(define (left-branch structure)
(car structure))
(define (right-branch structure)
(cdr structure))
(define (branch-length branch)
(car branch))
(define (branch-structure branch)
(cdr branch))
(define (total-weight tree)
(cond
((number? tree) tree)
(else (let ((left (left-branch tree))
(right (right-branch tree)))
(+ (total-weight (branch-structure left))
(total-weight (branch-structure right)))))))
(define (balanced? tree)
(cond
((number? tree) #t)
(else (let ((left (left-branch tree))
(right (right-branch tree)))
(let ((left-tree (branch-structure left))
(right-tree (branch-structure right)))
(and (= (* (branch-length left) (total-weight left-tree))
(* (branch-length right) (total-weight right-tree)))
(balanced? left-tree)
(balanced? right-tree)))))))