-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise2-29.lisp
More file actions
55 lines (45 loc) · 1.66 KB
/
exercise2-29.lisp
File metadata and controls
55 lines (45 loc) · 1.66 KB
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 car)
(define right-branch cadr)
(define branch-length car)
(define branch-structure cadr)
(define (total-weight x)
(if (not (pair? x))
x
(+ (total-weight (branch-structure (left-branch x)))
(total-weight (branch-structure (right-branch x))))))
(define x (make-mobile (make-branch 3 (make-mobile
(make-branch 1 2)
(make-branch 1 2)))
(make-branch 3 4)))
(display (total-weight x))
(newline)
(define (balanced? x)
(if (not (pair? x))
#t
(and (= (* (branch-length (left-branch x))
(total-weight (branch-structure (left-branch x))))
(* (branch-length (right-branch x))
(total-weight (branch-structure (right-branch x)))))
(balanced? (branch-structure (left-branch x)))
(balanced? (branch-structure (right-branch x))))))
(display (balanced? x))
(newline)
(define (make-mobile left right)
(cons left right))
(define (make-branch length structure)
(cons length structure))
; we just need to change the selectors to match the constructors and update any old data structures
(define right-branch cdr)
(define branch-structure cdr)
(define x (make-mobile (make-branch 3 (make-mobile
(make-branch 1 2)
(make-branch 1 2)))
(make-branch 3 4)))
(display (total-weight x))
(newline)
(display (balanced? x))
(newline)