-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.29.scm
90 lines (73 loc) · 2.53 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
(define (make-mobile left right)
(list left right))
(define (make-branch length structure)
(list length structure))
; a
(define (left-branch mobile) (car mobile))
(define (right-branch mobile) (cadr mobile))
(define (branch-length branch) (car branch))
(define (branch-structure branch) (cadr branch))
; b
(define (weight? structure) (number? structure))
(define (count-weight branch)
(let ((structure (branch-structure branch)))
(if (weight? structure)
structure
(total-weight structure))))
(define (total-weight mobile)
(+ (count-weight (left-branch mobile))
(count-weight (right-branch mobile))))
; c
(define the-empty-mobile '())
(define the-empty-mobile? null?)
(define (balanced? structure)
(if (weight? structure)
#t
(let ((left (left-branch structure))
(right (right-branch structure)))
(and (= (torque left)
(torque right))
(balanced? (branch-structure left))
(balanced? (branch-structure right))))))
(define (torque branch)
(* (branch-length branch)
(count-weight branch)))
; d
(define (make-mobile-2 left right)
(cons left right))
(define (make-branch-2 length structure)
(cons length structure))
(define (right-branch-2 mobile) (cdr mobile))
(define (branch-structure-2 branch) (cdr branch))
; 構成子の表現が変更されても選択子を変更するだけでよい。
; test
(define mobile
(make-mobile (make-branch 1 3)
(make-branch 1
(make-mobile (make-branch 1 3)
(make-branch 2 3)))))
(define mobile-balanced
(make-mobile (make-branch 2 3)
(make-branch 1
(make-mobile (make-branch 1 3)
(make-branch 1 3)))))
(define mobile-2
(make-mobile-2 (make-branch-2 1 3)
(make-branch-2 1
(make-mobile-2 (make-branch-2 1 3)
(make-branch-2 2 3)))))
(define mobile-balanced-2
(make-mobile-2 (make-branch-2 2 3)
(make-branch-2 1
(make-mobile-2 (make-branch-2 1 3)
(make-branch-2 1 3)))))
(define (main args)
(print (total-weight mobile))
(print (balanced? mobile))
(print (balanced? mobile-balanced))
(set! right-branch right-branch-2)
(set! branch-structure branch-structure-2)
(print (total-weight mobile-2))
(print (balanced? mobile-2))
(print (balanced? mobile-balanced-2))
)