-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch2.scm
4792 lines (3956 loc) · 157 KB
/
ch2.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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;;CODE FROM CHAPTER 2 OF STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS
;;; Examples from the book are commented out with ;: so that they
;;; are easy to find and so that they will be omitted if you evaluate a
;;; chunk of the file (programs with intervening examples) in Scheme.
;;; BEWARE: Although the whole file can be loaded into Scheme,
;;; you won't want to do so. For example, you generally do
;;; not want to use the procedural representation of pairs
;;; (cons, car, cdr as defined in section 2.1.3) instead of
;;; Scheme's primitive pairs.
;;; Some things require code from other chapters -- see ch2support.scm
(define (linear-combination a b x y)
(+ (* a x) (* b y)))
(define (linear-combination a b x y)
(add (mul a x) (mul b y)))
;;;SECTION 2.1.1
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equal-rat? x y)
(= (* (numer x) (denom y))
(* (numer y) (denom x))))
;: (define x (cons 1 2))
;:
;: (car x)
;: (cdr x)
;: (define x (cons 1 2))
;: (define y (cons 3 4))
;: (define z (cons x y))
;: (car (car z))
;: (car (cdr z))
(define (make-rat n d) (cons n d))
(define (numer x) (car x))
(define (denom x) (cdr x))
;;footnote -- alternative definitions
(define make-rat cons)
(define numer car)
(define denom cdr)
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
;: (define one-half (make-rat 1 2))
;:
;: (print-rat one-half)
;:
;: (define one-third (make-rat 1 3))
;:
;: (print-rat (add-rat one-half one-third))
;: (print-rat (mul-rat one-half one-third))
;: (print-rat (add-rat one-third one-third))
;; reducing to lowest terms in constructor
;; (uses gcd from 1.2.5 -- see ch2support.scm)
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
;: (print-rat (add-rat one-third one-third))
;;EXERCISE 2.1
(define (make-rat n d)
(let ((sign (if (= (positive? n) (positive? d)) 1 -1)))
(cons (* sign (abs n)) d)))
;;;SECTION 2.1.2
;; reducing to lowest terms in selectors
;; (uses gcd from 1.2.5 -- see ch2support.scm)
(define (make-rat n d)
(cons n d))
(define (numer x)
(let ((g (gcd (car x) (cdr x))))
(/ (car x) g)))
(define (denom x)
(let ((g (gcd (car x) (cdr x))))
(/ (cdr x) g)))
;; EXERCISE 2.2
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
(define (make-segment start end) (cons start end))
(define (start-segment seg) (car seg))
(define (end-segment seg) (cdr seg))
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (midpoint-segment seg)
(midpoint (start-segment seg) (end-segment seg)))
(define (midpoint p1 p2)
(make-point (/ (+ (x-point p1) (x-point p2)) 2)
(/ (+ (y-point p1) (y-point p2)) 2)))
;(let ((p1 (make-point 3 -5))
; (p2 (make-point -5 9)))
; (print-point (midpoint-segment (make-segment p1 p2))))
; (-1,2)
;;EXERCISE 2.3
; first representation
(define (make-rect corner opposite-corner)
(let ((left (min (x-point corner) (x-point opposite-corner)))
(right (max (x-point corner) (x-point opposite-corner)))
(bottom (min (y-point corner) (y-point opposite-corner)))
(top (max (y-point corner) (y-point opposite-corner))))
(cons (cons left right) (cons bottom top))))
(define (left rect) (car (car rect)))
(define (right rect) (cdr (car rect)))
(define (bottom rect) (car (cdr rect)))
(define (top rect) (cdr (cdr rect)))
(define (width rect) (- (right rect) (left rect)))
(define (height rect) (- (top rect) (bottom rect)))
; alternative representation
(define (make-rect bottom-left width height)
(cons bottom-left (cons width height)))
(define (left rect) (x-point (car rect)))
(define (right rect) (+ (left rect) (width rect)))
(define (bottom rect) (y-point (car rect)))
(define (top rect) (+ (bottom rect) (height rect)))
(define (width rect) (car (cdr rect)))
(define (height rect) (cdr (cdr rect)))
; higher-level procedures that work using either representation
(define (perimeter rect) (* 2 (+ (width rect) (height rect))))
(define (area rect) (* (width rect) (height rect)))
;;;SECTION 2.1.3
(define (cons x y)
(define (dispatch m)
(cond ((= m 0) x)
((= m 1) y)
(else (error "Argument not 0 or 1 -- CONS" m))))
dispatch)
(define (car z) (z 0))
(define (cdr z) (z 1))
;; EXERCISE 2.4
(define (cons x y)
(lambda (m) (m x y)))
(define (car z)
(z (lambda (p q) p)))
(define (cdr z)
(z (lambda (p q) q)))
; Here is the series of substitutions performed during evaluation of
; (car (cons x y)), showing that this expression evaluates to x for any objects
; x and y.
;
; (car (cons x y))
; (car (lambda (m) (m x y)))
; ((lambda (m) (m x y)) (lambda (p q) p))
; ((lambda (p q) p) x y)
; x
;;EXERCISE 2.5
; To establish that 2ᵃ3ᵇ is a valid representation of the pair (a, b), we must
; show that the customary invariants for cons, car, and cdr hold true for any
; nonnegative integers a and b. Thus we must show that (car (cons a b)) is a and
; (cdr (cons a b)) is b. Let f(a,b) = 2ᵃ3ᵇ, and observe that the prime
; factorization of f(a,b) includes a twos and b threes. Now let g(z) be the
; function that counts the number of twos in the prime factorization of z, and
; similarly h(z) for the number of threes. By the prior observation,
; g(f(a,b)) = a and h(f(a,b)) = b. If we make our cons, car, and cdr procedures
; equivalent to f, g, and h respectively, then we know that (car (cons a b))
; returns a and (cdr (cons a b) returns b, so our representation is valid.
(define (cons a b)
(* (expt 2 a) (expt 3 b)))
(define (car z)
(if (even? z)
(+ 1 (car (/ z 2)))
0))
(define (cdr z)
(if (= (remainder z 3) 0)
(+ 1 (cdr (/ z 3)))
0))
;; EXERCISE 2.6
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
(define one (lambda (f) (lambda (x) (f x))))
(define two (lambda (f) (lambda (x) (f (f x)))))
(define (+ a b)
(lambda (f) (lambda (x) ((a f) ((b f) x)))))
; Change a Church numeral to a standard number
(define (church->integer n) ((n 1+) 0))
;;;SECTION 2.1.4
(define (add-interval x y)
(make-interval (+ (lower-bound x) (lower-bound y))
(+ (upper-bound x) (upper-bound y))))
(define (mul-interval x y)
(let ((p1 (* (lower-bound x) (lower-bound y)))
(p2 (* (lower-bound x) (upper-bound y)))
(p3 (* (upper-bound x) (lower-bound y)))
(p4 (* (upper-bound x) (upper-bound y))))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
(define (div-interval x y)
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y)))))
;; EXERCISE 2.7
(define (make-interval a b) (cons a b))
(define (upper-bound i) (max (car i) (cdr i)))
(define (lower-bound i) (min (car i) (cdr i)))
;;EXERCISE 2.8
; The minimum value of the difference of two intervals must be the minimum
; value of the first interval minus the maximum value of the second. The maximum
; value of the difference must be the maximum value of the first minus the
; minimum value of the second.
(define (sub-interval x y)
(make-interval (- (lower-bound x) (upper-bound y))
(- (upper-bound x) (lower-bound y))))
;;EXERCISE 2.9
; First we are to show that the width of the sum of two intervals is a function
; only of their widths. Let i1, i2 be any two intervals and let ub and lb be the
; functions that compute an interval's upper and lower bounds respectively. By
; definition of the sum of two intervals given above, we know that
;
; ub(i1 + i2) = ub(i1) + ub(i2) and
; lb(i1 + i2) = lb(i1) + lb(i2).
;
; The width of an interval is defined as
;
; width(i) = 1/2 * (ub(i) - lb(i)).
;
; Thus:
;
; width(i1 + i2) = 1/2 * (ub(i1 + i2) - lb(i1 + i2))
; = 1/2 * ((ub(i1) + ub(i2)) - (lb(i1) + lb(i2)))
; = 1/2 * (ub(i1) - lb(i1)) + 1/2 * (ub(i2) - lb(i2))
; = width(i1) + width(i2)
;
; which shows that the width of a sum of two intervals is a function only of
; their widths.
;
; Second we are to show that the same property is true of the difference of two
; intervals. By the definition of the difference of two intervals, for any two
; intervals i3 and i4 we know that
;
; ub(i3 - i4) = lb(i3) - ub(i4) and
; lb(i3 - i4) = ub(i3) - lb(i4).
;
; Thus:
;
; width(i3 - i4) = 1/2 * (ub(i3 - i4) - lb(i3 - i4))
; = 1/2 * ((lb(i3) - ub(i4)) - (ub(i3) - lb(i4)))
; = 1/2 * (lb(i3) - ub(i3)) + 1/2 * (lb(i4) - ub(i4))
; = (-1/2) * (ub(i3) - lb(i3)) + (-1/2) * (ub(i4) - lb(i4))
; = -(width(i3) + width(i4))
;
; which shows that the width of a difference of two intervals is a function only
; of their widths.
;
; Finally we are to show by counterexample that the property does not hold for
; multiplication and division of intervals. For a given operation f over two
; intervals, if the property *does* hold for that operation, then for any
; intervals a, b, c, and d,
;
; width(a) = width(b) and
; width(c) = width(d)
;
; implies
;
; width(f(a,c)) = width(f(b,d)).
;
; We can prove the property does not hold for f by finding an a, b, c, and d for
; which the first and second equalities hold true but not the third.
;
; The intervals a=(10,20), b=(20,30), c=(30,60), and d=(60,90) satisfactorily
; prove the assertion for both multiplication and division, as shown by running
; the small test program below.
(define (width i) (/ (- (upper-bound i) (lower-bound i)) 2))
(define (test-counterexample f a b c d)
(display "test with (a b c d) = ") (display (list a b c d)) (newline)
(display "width(a) = ") (display (width a)) (newline)
(display "width(b) = ") (display (width b)) (newline)
(display "width(c) = ") (display (width c)) (newline)
(display "width(d) = ") (display (width d)) (newline)
(display "width(f(a,c)) = ") (display (width (f a c))) (newline)
(display "width(f(b,d)) = ") (display (width (f b d))) (newline)
(if (and (= (width a) (width b))
(= (width c) (width d))
(not (= (width (f a c)) (width (f b d)))))
(display "success: the property does not hold!")
(display "inconclusive result: width(f(a,c)) = width(f(b,d))"))
(newline))
;(define a (make-interval 10 20))
;(define b (make-interval 20 30))
;(define c (make-interval 30 60))
;(define d (make-interval 60 90))
;(test-counterexample mul-interval a b c d) ; success
;(test-counterexample div-interval a b c d) ; success
;(test-counterexample add-interval a b c d) ; success
;(test-counterexample sub-interval a b c d) ; success
;;EXERCISE 2.10
(define (contains-interval? i n)
(and (>= n (lower-bound i))
(<= n (upper-bound i))))
(define (div-interval x y)
(if (contains-interval? y 0)
(error "division by zero")
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))))
;;EXERCISE 2.11
(define (mul-interval x y)
(define (both p i) (and (p (upper-bound i)) (p (lower-bound i))))
(define (pos? i) (both (lambda (x) (>= x 0)) i))
(define (neg? i) (both (lambda (x) (<= x 0)) i))
; Define the following values as procedures instead of precomputing them per
; the exercise prompt, which requires limiting the multiplications performed.
(define (p1) (* (lower-bound x) (lower-bound y)))
(define (p2) (* (lower-bound x) (upper-bound y)))
(define (p3) (* (upper-bound x) (lower-bound y)))
(define (p4) (* (upper-bound x) (upper-bound y)))
(cond ((pos? x)
(cond ((pos? y) (make-interval (p1) (p4)))
((neg? y) (make-interval (p2) (p3)))
(else (make-interval (p3) (p4)))))
((neg? x)
(cond ((pos? y) (make-interval (p2) (p3)))
((neg? y) (make-interval (p1) (p4)))
(else (make-interval (p1) (p2)))))
(else
(cond ((pos? y) (make-interval (p2) (p4)))
((neg? y) (make-interval (p1) (p3)))
(else (let ((p1 (p1)) (p2 (p2)) (p3 (p3)) (p4 (p4)))
(make-interval (max p1 p2 p3 p4)
(min p1 p2 p3 p4))))))))
;;;SECTION 2.1.4 again
(define (make-center-width c w)
(make-interval (- c w) (+ c w)))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
(/ (- (upper-bound i) (lower-bound i)) 2))
;;EXERCISE 2.12
(define (make-center-percent c p)
(let ((width (* c (/ p 100))))
(make-interval (- c width) (+ c width))))
(define (percent i)
(* (/ (width i) (center i)) 100))
;;EXERCISE 2.13
; We are to derive a formula for approximating the tolerance of the product of
; two intervals in terms of the tolerances of the factors.
;
; Using our previous definitions of operations on intervals, for some interval
; i, the upper bound, lower bound, width, center, and tolerance have the
; following equivalencies:
;
; ub(i) = center(i) * (1 + tol(i))
; lb(i) = center(i) * (1 - tol(i))
; width(i) = (ub(i) - lb(i)) / 2
; center(i) = (ub(i) + lb(i)) / 2
; tol(i) = width(i) / center(i)
;
; The bounds of the product of two intervals i and j (with all endpoints
; positive) are defined as
;
; ub(ij) = ub(i) * ub(j)
; lb(ij) = lb(i) * lb(j).
;
; Using these facts we can derive the approximation formula:
;
; ub(ij) = ub(i) * ub(j)
; = center(i) * (1 + tol(i)) * center(j) * (1 + tol(j))
;
; lb(ij) = lb(i) * lb(j)
; = center(i) * (1 - tol(i)) * center(j) * (1 - tol(j))
;
; tol(ij) = width(ij) / center(ij)
; = ((ub(ij) - lb(ij)) / 2) / ((ub(ij) + lb(ij)) / 2)
; = (ub(ij) - lb(ij)) / (ub(ij) + lb(ij))
; = (ub(i) * ub(j) - lb(i) * lb(j)) / (ub(i) * ub(j) + lb(i)*lb(j))
;
; center(i) * (1 + tol(i)) * center(j) * (1 + tol(j)) -
; center(i) * (1 - tol(i)) * center(j) * (1 - tol(j))
; = —————————————————————————————————————————————————————
; center(i) * (1 + tol(i)) * center(j) * (1 + tol(j)) +
; center(i) * (1 - tol(i)) * center(j) * (1 - tol(j))
;
; (1 + tol(i)) * (1 + tol(j)) - (1 - tol(i)) * (1 - tol(j))
; = —————————————————————————————————————————————————————————
; (1 + tol(i)) * (1 + tol(j)) + (1 - tol(i)) * (1 - tol(j))
;
; (1 + tol(i) + tol(j) + tol(i) * tol(j)) -
; (1 - tol(i) - tol(j) + tol(i) * tol(j))
; = —————————————————————————————————————————
; (1 + tol(i) + tol(j) + tol(i) * tol(j)) +
; (1 - tol(i) - tol(j) + tol(i) * tol(j))
;
; 2 * tol(i) + 2 * tol(j) tol(i) + tol(j)
; = ——————————————————————— = ———————————————————
; 2 + 2 * tol(i) * tol(j) 1 + tol(i) * tol(j)
;
; Since we assume small tolerances, tol(i) and tol(j) are small fractions, and
; so their product will be very small. As an approximation we can assume it's 0,
; which yields this simple approximation for the tolerance of the product of
; intervals:
;
; tol(ij) = tol(i) + tol(j)
;; parallel resistors
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ((one (make-interval 1 1)))
(div-interval one
(add-interval (div-interval one r1)
(div-interval one r2)))))
;;EXERCISE 2.14
; Below, a test procedure is used to evaluate different implementations of
; several intervallic expressions. For a given expression, implementations may
; produce inconsistent results when the same inputs are used in positions that
; affect the final result differently. For example:
;
; par1(r1,r2) = (a*b)/(c+d) where a=r1 b=r2 c=r1 d=r2
; par2(r1,r2) = 1/(1/a+1/b) where a=r1 b=r2
;
; In par1, input r1 is used in terms (a, c) that affect the final result in
; opposite directions whereas only one direction in par2. For the same input
; values, par1 generates a wider result interval than par2.
;
; Where implementations do not use inputs in "contradictory" ways, the results
; are consistent; see xxy1 and xxy2 below for example.
(define (test f a-center a-width b-center b-width)
(let ((a (make-center-width a-center a-width))
(b (make-center-width b-center b-width)))
(let ((result (f a b)))
(let ((result-center (center result))
(result-width (width result)))
(display "; c=") (display result-center)
(display " w=") (display result-width) (newline)))))
(define (percent-error expected value)
(* 100 (abs (/ (- value expected) expected))))
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ((one (make-interval 1 1)))
(div-interval one
(add-interval (div-interval one r1)
(div-interval one r2)))))
;(test par1 100 1 100 1) ; c=50.02000200020002 w=1.50020002000200
;(test par2 100 1 100 1) ; c=50. w=.5000000000000036
;(test par1 150 5 300 10) ; c=100.44493882091213 w=10.014831294030401
;(test par2 150 5 300 10) ; c=100. w=3.3333333333333286
(define (div-twice a b)
(div-interval (mul-interval (div-interval a b) b) b))
(define (div-thrice a b)
(div-interval (mul-interval (div-twice a b) b) b))
;(test div-interval 100 1 100 1) ; c=1.0002000200020003 w=2.0002000200020076e-2
;(test div-twice 100 1 100 1) ; c=1.0008001600240033 w=.0400120020002801
;(test div-thrice 100 1 100 1) ; c=1.0018006601460259 w=.06003801020198035
;(test div-interval 150 5 300 10) ; c=.5011123470522802 w=3.3370411568409336e-2
;(test div-twice 150 5 300 10) ; c=.5044543374729801 w=.06688930105258473
;(test div-thrice 150 5 300 10) ; c=.5100408410748722 w=.10070580700417978
(define (xxy1 x y)
(mul-interval (mul-interval x x) y))
(define (xxy2 x y)
(mul-interval x (mul-interval x y)))
;(test xxy1 100 1 100 1) ; c=1000300 w=30001
;(test xxy2 100 1 100 1) ; c=1000300 w=30001
;(test xxy1 150 5 300 10) ; c=6772500 w=675250
;(test xxy2 150 5 300 10) ; c=6772500 w=675250
(define (add-twice a b)
(add-interval (sub-interval (add-interval a b) b) b))
(define (add-thrice a b)
(add-interval (sub-interval (add-twice a b) b) b))
(define (add-alt a b)
(sub-interval (mul-interval (add-interval a b)
(make-interval 2 2))
(add-interval a b)))
;(test add-interval 150 5 300 10) ; c=450 w=15
;(test add-twice 150 5 300 10) ; c=450 w=35
;(test add-thrice 150 5 300 10) ; c=450 w=55
;(test add-alt 150 5 300 10) ; c=450 w=45
(define (quad-sum1 a b)
(define sum (add-interval a b))
(define double-sum (add-interval sum sum))
(add-interval double-sum double-sum))
(define (quad-sum2 a b)
(let ((2a+b (add-interval a (add-interval a b)))
(2b (add-interval b b)))
(add-interval (add-interval 2a+b 2a+b) 2b)))
;(test quad-sum1 150 5 300 10) ; c=1800 w=60
;(test quad-sum2 150 5 300 10) ; c=1800 w=60
;;EXERCISE 2.15
; The observation is correct: formulas produce tighter error bounds when
; variables that carry uncertainty are not repeated inside the formula. Not only
; are the error bounds on the results tighter, but also they are more correct
; for this (and probably most) problem domains. The reason is that variables
; which simulate a real-world quantity can only have one actual value at any
; given time. When we include such a variable in a formula more than once, and
; that variable carries uncertainty, then the overall uncertainty of the formula
; will erroneously reflect that *each* occurrence of that variable could have
; any value within the variable's entire range of possibilities. It is as though
; we had used several variables with identical uncertainties instead of just
; one! Using an uncertainty-carrying variable only once inside a formula avoids
; this problem.
;; EXERCISE 2.16
;; Equivalent algebraic expressions of intervals may produce different results
;; because the ordinary rules of algebra do not hold for intervals. Our
;; expectations about algebraic equivalency are based on ordinary numbers. While
;; intervals are conceptually and representionally pairs of ordinary numbers --
;; bounds -- the intervallic primitives mul-interval etc. are mostly not
;; equivalent to performing the corresponding numeric operations on those
;; bounds. Thus, one may write expressions of intervallic primitives that appear
;; algebraically equivalent but translate into numeric operations that are
;; inequivalent.
;;
;; To recover algebraic soundness, we have to build the system in such a way
;; that the mathematical meaning of a given expression is not lost as it is
;; manipulated, used in formulas, etc. This requires, first of all, that we make
;; a distinction between pure quantities and variables. (The inaccuracies
;; introduced by "double-counting" variables as in exercise 2.15 can be said to
;; be a result of treating variables erroneously as pure quantities.) So we'll
;; need a way to represent expressions symbolically. This should be
;; straightforward -- e.g. '((+ x (* 3 y))).
;;
;; Now we can rethink the problem in terms of the actual mathematical meaning of
;; expressions. An expression is essentially a function of multiple variables.
;; When we evaluate an expression, the input intervals represent the domain of
;; a partial function that is equivalent to the original expression but only
;; defined for these values. So the problem we are facing can be conceptualized
;; as, what are the minimum and maximum values of this partial function?
;;
;; We know that minima and maxima must occur at a critical point of the function
;; (where its gradient is zero) or at the edge of the domain (where at least one
;; of the variables' values is equal to the lower or upper bound of its
;; interval in the domain). To catch possible minima or maxima at the
;; edge, we can just hold each of the input variables constant in our expression
;; and then find the minima and maxima of the resulting expression. Thus, if we
;; can devise a general way to find the critical points of a function in
;; multiple variables, we'll be able to find the min and max values of
;; expressions.
;;
;; Doing this in a precise way would require building a symbolic differentiation
;; system to get an expression for the gradient of a function, then a
;; zero-finding algorithm to find the critical points. The former should be
;; possible; the text implements symbolic differentiation with respect to one
;; variable in section 2.3.2, and this could be extended. Finding zeroes is
;; problematic, as there are expressions representable in this system for which
;; no algebraic solution for the roots exists, per the Abel-Ruffini theorem.
;; (See Wikipedia, "Algebraic solution," accessed 2019-07-23.) Therefore, we are
;; forced to use approximation.
;;
;; Since we can't get an exact answer, there's little use in taking a symbolic
;; approach for any part of the problem, and thus we might as well avoid the
;; difficulty of building a differentiation system and just approximate the
;; minimum and maximum values by sampling. We can let the user specify a "grid
;; spacing" over the input domain and evaluate the expression at all points on
;; the grid, taking the smallest and largest results as the lower and upper
;; bounds of our result interval. That could get computationally expensive for
;; equations of many variables or when the grid is dense relative to the
;; interval sizes. Another approach would be a search that starts with a coarse
;; grid and iteratively "zooms in" on local minima and maxima until reaching
;; some stop condition (such as % change falling below a certain threshold).
;; However, as this exercise is defined as a proof of concept, I will stick with
;; the grid approach to keep things simple.
;;
;; Below I implement a system for evaluating algebraic expressions with interval
;; inputs. It uses a form of normal-order evaluation. The expression to be
;; evaluated is expanded maximally using placeholders for its inputs. Then the
;; expanded expression is evaluated at each point in a grid of configurable
;; density spanning the input domain. The minimum and maximum values obtained
;; are returned the bounds of the result interval.
;;
;; USAGE
;; Formulas are represented as nested lists. The operations + - * / are
;; supported; they must be quoted. Within a formula, use exact numbers rather
;; than intervals. (Intervals can only be used to set the value ranges of
;; parameters when evaluating.) A formula's parameters are defined implicitly by
;; the set of symbols appearing inside it (other than '+, '-, '*, or '/).
;;
;; A formula may invoke an external formula; to do so, write
;;
;; (list formula (list name1 value1) (list name2 value2) ... )
;;
;; where formula is the name of the external formula (not quoted) and the
;; name/value pairs set the values of parameters name1, name2, etc.
;;
;; To evaluate a formula, just do
;;
;; (eval formula grid-spacing (list name1 value1) (list name2 value2) ... )
;;
;; where name1, name2, etc. are parameter names and value1, value2, etc. are
;; intervals. Grid-spacing is the sample grid spacing. The return value is an
;; interval giving the maximum and minimum possible results.
;;
;; EXAMPLES
;; Here is an example which ties together most of the above rules.
;;
;; (define avg '(/ (+ a b) 2))
;; (define f '(* (+ a 2) (- b 4)))
;; (define g (list avg (list 'a (list f '(a a) '(b b)))
;; (list 'b (list f '(a b) '(b a)))))
;;
;; (eval g 1/10 (list 'a (make-interval 8 10))
;; (list 'b (make-interval 6 12)))
;; ;Value: (26 . 90)
;;
;; The next example shows the system's ability to find a maximum or minimum
;; inside the input domain, not just at its extreme points. This is
;; (x - 5)² + (y - 3)² for x ∈ [0, 10], y ∈ [0, 10] with the minimum occurring
;; at (5,3).
;;
;; (define f '(+ (* (- x 5) (- x 5)) (* (- y 3) (- y 3))))
;; (eval f 1 (list 'x (make-interval 0 10)) (list 'y (make-interval 0 10)))
;; ;Value: (0 . 74)
;;
;; Here are the parallel resistors procedures from earlier translated into the
;; new system. The accompanying test procedure is used to show that the new
;; system provides reasonably correct results, as well as identical results for
;; algebraically-equivalent expressions. (Compare the lowest-error results from
;; exercise 2.15.)
;;
;; (define (test expr r1-center r1-width r2-center r2-width)
;; (let ((r1 (make-center-width r1-center r1-width))
;; (r2 (make-center-width r2-center r2-width)))
;; (let ((result (eval expr 1/10 (list 'r1 r1) (list 'r2 r2))))
;; (let ((result-center (center result))
;; (result-width (width result)))
;; (display "; c=") (display result-center)
;; (display " w=") (display result-width) (newline)))))
;;
;; (define par1 '(/ (* r1 r2) (+ r1 r2)))
;; (define par2 '(/ 1 (+ (/ 1 r1) (/ 1 r2))))
;;
;; (test par1 100 1 100 1) ; c=50 w=1/2
;; (test par2 100 1 100 1) ; c=50 w=1/2
;; (test par1 150 5 300 10) ; c=100 w=10/3
;; (test par2 150 5 300 10) ; c=100 w=10/3
;; IMPLEMENTATION
;; representation of variable bindings
(define (var b) (car b))
(define (val b) (cadr b))
(define (make-binding var val) (list var val))
;; representation of expressions
(define (primitive? expr)
(if (memq expr '(+ - * /)) true false))
(define (apply-primitive op args)
(apply (lookup op (list (list '+ +) (list '- -) (list '* *) (list '/ /))
args)))
(define (var? expr)
(and (symbol? expr) (not (primitive? expr))))
(define (compound? expr) (pair? expr))
(define (op comp-expr) (car comp-expr))
(define (args comp-expr) (cdr comp-expr))
(define (make-compound op args) (cons op args))
;; calculate the max and min possible values of expr over domain
(define (eval expr grid-spacing . domain)
(let ((self-bindings
(map (lambda (binding) (list (var binding) (var binding)))
domain)))
(let ((expanded-expr (expand expr self-bindings)))
(fold-grid (lambda (min-max incr-bindings)
(let ((result (eval-exact expanded-expr incr-bindings)))
(let ((min-val (car min-max))
(max-val (cdr min-max)))
(cons (if min-val (min result min-val) result)
(if max-val (max result max-val) result))))
(cons false false)
domain
grid-spacing))))
;; fully expand an expression with specified variable bindings
(define (expand expr bindings)
(cond (or ((number? expr) (primitive? expr)) expr)
((var? expr) (lookup expr bindings))
((compound? expr)
(if (primitive? (op expr))
(make-compound (op expr)
(map (lambda (arg) (expand arg bindings))
(args expr)))
(expand (op expr)
(map (lambda (arg)
(make-binding (var arg)
(expand (val arg) bindings)))
(args expr)))))
(else (error "Invalid expression -- EXPAND" expr))))
;; evaluate an expression with its variables bound to discrete values
(define (eval-exact expr bindings)
(cond ((number? expr) expr)
((var? expr) (lookup expr bindings))
((compound? expr)
(if (primitive? (op expr))
(apply-primitive op
(map (lambda (arg) (eval-exact arg bindings))
(args expr)))
(eval-exact
(op expr)
(map (lambda (arg)
(make-binding (var arg)
(eval-exact (val arg) bindings)))
(args expr)))))
(else (error "Invalid expression -- EVAL" expr))))
;; fold over all grid points within the domain
(define (fold-grid f init domain grid-spacing)
(define (iter acc outer-bindings inner-domain inner-bindings)
(cond ((null? inner-bindings) (f acc outer-bindings))
;; include upper bounds even if they do not fall on the grid
((>= (val (car inner-bindings))
(upper-bound (val (car inner-domain))))
(iter acc
(cons (make-binding (var (car inner-bindings))
(upper-bound (val (car inner-domain))))
outer-bindings)
(cdr inner-domain)
(cdr inner-bindings)))
(else
(let ((result (iter acc
(cons (car inner-bindings) outer-bindings)
(cdr inner-domain)
(cdr inner-bindings))))
(iter result
outer-bindings
inner-domain
(cons (make-binding (var (car inner-bindings))
(+ (val (car inner-bindings))
grid-spacing))
(cdr inner-bindings)))))))
(iter init
'()
domain
(map (lambda (binding) (list (var binding)
(lower-bound (val binding))))
domain)))
;; look up a value in a list of items of the form (list key value)
(define (lookup key assoc-list)
(cond ((null? assoc-list) false)
((eq? (car (car assoc-list)) key) (cadr (car assoc-list)))
(else (lookup key (cdr assoc-list)))))
;;;SECTION 2.2.1
;: (cons 1
;: (cons 2
;: (cons 3
;: (cons 4 nil))))
;: (define one-through-four (list 1 2 3 4))
;:
;: one-through-four
;: (car one-through-four)
;: (cdr one-through-four)
;: (car (cdr one-through-four))
;: (cons 10 one-through-four)
(define (list-ref items n)
(if (= n 0)
(car items)
(list-ref (cdr items) (- n 1))))
;: (define squares (list 1 4 9 16 25))
;: (list-ref squares 3)
(define (length items)
(if (null? items)
0
(+ 1 (length (cdr items)))))
;: (define odds (list 1 3 5 7))
;: (length odds)
(define (length items)
(define (length-iter a count)
(if (null? a)
count
(length-iter (cdr a) (+ 1 count))))
(length-iter items 0))
;: (append squares odds)
;: (append odds squares)
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1) (append (cdr list1) list2))))
;; EXERCISE 2.17
(define (last-pair list)
(if (null? (cdr list))
(car list)
(last-pair (cdr list))))
;: (last-pair (list 23 72 149 34)) ; 34
;; EXERCISE 2.18
(define (reverse list)
(define (iter old new)
(if (null? old)
new
(iter (cdr old) (cons (car old) new))))
(iter list '()))
;: (reverse (list 1 4 9 16 25)) ; (25 16 9 4 1)
;; EXERCISE 2.19
(define us-coins (list 50 25 10 5 1))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
;(cc 100 us-coins) ; 292
;(cc 100 uk-coins) ; 104561
(define (cc amount coin-values)
(cond ((= amount 0) 1)
((or (< amount 0) (no-more? coin-values)) 0)
(else
(+ (cc amount
(except-first-denomination coin-values))
(cc (- amount
(first-denomination coin-values))
coin-values)))))
(define (first-denomination coin-values) (car coin-values))
(define (except-first-denomination coin-values) (cdr coin-values))
(define (no-more? coin-values) (null? coin-values))
;; EXERCISE 2.20
(define (same-parity x . xs)
(define filter (if (even? x) even? odd?))
(define (iter acc xs)
(if (null? xs)
acc
(iter (if (filter (car xs))
(cons (car xs) acc)
acc)
(cdr xs))))
(reverse (iter (list x) xs)))
;: (same-parity 1 2 3 4 5 6 7) ; (1 3 5 7)
;: (same-parity 2 3 4 5 6 7) ; (2 4 6)
;; Mapping over lists
(define (scale-list items factor)
(if (null? items)
nil
(cons (* (car items) factor)
(scale-list (cdr items) factor))))
;: (scale-list (list 1 2 3 4 5) 10)
;: (map + (list 1 2 3) (list 40 50 60) (list 700 800 900))
;: (map (lambda (x y) (+ x (* 2 y)))
;: (list 1 2 3)
;: (list 4 5 6))
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
;: (map abs (list -10 2.5 -11.6 17))
;: (map (lambda (x) (* x x))
;: (list 1 2 3 4))
(define (scale-list items factor)
(map (lambda (x) (* x factor))
items))
;; EXERCISE 2.21
(define (square-list items)
(if (null? items)
'()
(cons (square (car items)) (square-list (cdr items)))))