summaryrefslogtreecommitdiffstats
path: root/ps06_rule_systems/bnewbold_ps06_work.scm
blob: 4358ccfc5a01758b0433cf8fdf776ef4ffc4a44b (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

(load "load")

;;; Problem 6.4

(define algebra-3
  (rule-simplifier
   (list

    ;; Sums

    (rule (+ (? a)) none (? a))

    (rule (+ (?? a) (+ (?? b)))
	  none
	  (+ (?? a) (?? b)))

    (rule (+ (+ (?? a)) (?? b))
	  none
	  (+ (?? a) (?? b)))

    (rule (+ (?? a) (? y) (? x) (?? b))
	  (expr<? x y)
	  (+ (?? a) (? x) (? y) (?? b)))
    

    ;; Products

    (rule (* (? a)) none (? a))

    (rule (* (?? a) (* (?? b)))
	  none
	  (* (?? a) (?? b)))

    (rule (* (* (?? a)) (?? b))
	  none
	  (* (?? a) (?? b)))

    (rule (* (?? a) (? y) (? x) (?? b))
	  (expr<? x y)
	  (* (?? a) (? x) (? y) (?? b)))

    ;; Distributive law

    (rule (* (? a) (+ (?? b)))
	  none
	  (+ (?? (map (lambda (x) `(* ,a ,x)) b))))

    ;; Numerical simplifications below

    (rule (+ 0 (?? x)) none (+ (?? x)))

    (rule (+ (? x number?) (? y number?) (?? z))
	  none
	  (+ (? (+ x y)) (?? z)))


    (rule (* 0 (?? x)) none 0)
     
    (rule (* 1 (?? x)) none (* (?? x)))

    (rule (* (? x number?) (? y number?) (?? z))
	  none
	  (* (? (* x y)) (?? z)))

    ;; Collect terms

    (rule (+ (?? s) (? x) (? x) (?? e))
	  none
	  (+ (?? s) (* 2 (? x)) (?? e)))

    (rule (+ (?? s) (* (?? x)) (* (?? x)) (?? e))
	  none
	  (+ (?? s) (* 2 (?? x)) (?? e)))

    (rule (+ (?? s) (? x) (?? m) (* (? n number?) (? x)) (?? e))
	  none
	  (+ (?? s) (?? m) (* (? (+ 1 n)) (? x)) (?? e)))

    (rule (+ (?? s) (* (? n number?) (?? x)) (* (? p number?) (?? x)) (?? e))
	  none
	  (+ (?? s) (* (? (+ n p)) (? x)) (?? e)))

    )))

#| Test!

(algebra-3 '(+ x (* 4 x)))
;Value 15: (* 5 x)

(algebra-3 '(+ (* 8 1 f 34) (* 3 f)))
;Value 16: (* 275 x)

(algebra-3 '(+ x x))
;Value 42: (* 2 x)

(algebra-3 '(+ 4 s u s p))
;Value 39: (+ 4 p u (* 2 s))

(algebra-3 '(+ 1 2))
;Value: 3

(algebra-3 '(+ (* -2 h) (* 2 h)))
;Value: 0

(algebra-3 '(+ h (* 4 h)))
;Value 83: (* 5 h)

(algebra-3 '(+ (* w h) (* 4 h)))
;Value 84: (+ (* 4 h) (* h w))

(algebra-3 '(+ (* -1 h) (* 2 h)))
;Value 85: (h)

(algebra-3 '(+ x (* a x)))
;Value 86: (+ x (* a x))

(algebra-3 '(+ y (* x -2 w) (* x 4 y) (* w x) z (* 5 z) (* x w) (* x y 3)))
;Value 87: (+ y (* 6 z) (* 7 (x y)))

|#

;;; Problem 6.5