-
Notifications
You must be signed in to change notification settings - Fork 6
/
Chapter 2.scm
1760 lines (1601 loc) · 55.1 KB
/
Chapter 2.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
;-- 2.1
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ (if (or (and (< n 0) (< d 0)) (and (> n 0) (< d 0)))
(- n)
n)
g)
(/ (if (or (and (< n 0) (< d 0)) (and (> n 0) (< d 0)))
(- d)
d)
g))))
; Clever version, from http://community.schemewiki.org/?sicp-ex-2.1
(define (make-rat n d)
(let ((g ((if (< d 0) - +) (gcd n d))))
(cons (/ n g) (/ d g))))
;-- 2.2
(define (make-segment x y) (cons x y))
(define (start-segment s) (car s))
(define (end-segment s) (cdr s))
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (average x y) (/ (+ x y) 2))
(define (midpoint-segment s)
(make-point (average (x-point (start-segment s))
(x-point (end-segment s)))
(average (y-point (start-segment s))
(y-point (end-segment s)))))
; Given:
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
;-- 2.3
(define (rectangle a b c d) ; Where a, b, c and d are (x,y) pairs representing
; points coordinates as : a b
(cons (cons a b) (cons c d))) ; d c
(define (point_a r) (car (car r)))
(define (point_b r) (cdr (car r)))
(define (point_c r) (car (cdr r)))
(define (point_d r) (cdr (cdr r)))
(define (distance a b)
(sqrt (+ (square (- (x-point b) (x-point a)))
(square (- (y-point b) (y-point a))))))
(define (width r)
(distance (point_a r) (point_b r)))
(define (height r)
(distance (point_b r) (point_c r)))
(define (perimeter r)
(+ (* 2 (height r))
(* 2 (width r))))
(define (area r)
(* (height r) (width r)))
(define r_test (rectangle (cons 1 3) (cons 4 3) (cons 4 (- 1)) (cons 1 (- 1))))
(perimeter r_test)
(area r_test)
;-- 2.4
(define (cons24 x y)
(lambda (m) (m x y)))
(define (car24 z)
(z (lambda (p q) p)))
(define (cdr24 z)
(z (lambda (p q) q)))
;-- 2.5
;-- 2.6
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
(lambda (f) (lambda (x) (f ((n f) x)))))
; we'll find (one) by substitution
; one => (add-1 zero)
; (lambda (f) (lambda (x) (f ((zero f) x))))
; (lambda (f) (lambda (x) (f x)))
;-- 2.7 - 2.16
;-- 2.17
(define (last-pair l)
(if (null? (cdr l))
l
(last-pair (cdr l))))
; Test:
(last-pair (list 1 2 3 4))
;-- 2.18
(define (reverse alist)
(if (null? (cdr alist))
alist
(append (reverse (cdr alist))
(list (car alist)))))
; Test:
(reverse (list 1 2 3 4))
;-- 2.19
(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))
(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)))))
;-- 2.20
(define (same-parity . numberlist)
(define (filter li condition)
(if (null? li)
li
(if (condition (car li))
(append (list (car li)) (filter (cdr li) condition))
(filter (cdr li) condition))))
(if (even? (car numberlist))
(filter numberlist even?)
(filter numberlist (lambda (x) (not (even? x))))))
;-- 2.21
(define (square-list items)
(if (null? items)
nil
(cons (* (car items) (car items))
(square-list (cdr items)))))
(define (square-list items)
(map (lambda (x) (* x x)) items))
;-- 2.22
; The first version won't work because the items are popped from the
; first list and then pushed in the second � resulting in a reverse
; order.
; The second version won't work because "cons"-ing a list to an int
; results in a list-in-a-list ((a b) c); contrary to "cons"-ing an
; int to a list which gives a list (a b c).
;-- 2.23
(define (for-each fun lis)
(cond ((null? lis) #t)
(else (fun (car lis))
(for-each fun (cdr lis)))))
;-- 2.24
(list 1 (list 2 (list 3 4)))
; Interpreter: (1 (2 (3 4)))
; Boxes: [.|.]->[.|x]
; v v
; [1] [.|.]-> [.|x]
; v v
; [2] [.|.]->[.|x]
; v v
; [3] [4]
;
; Tree: (1 (2 (3 4)))
; / \
; 1 (2 (3 4))
; / \
; 2 (3 4)
; / \
; 3 4
;-- 2.25
; Give combinations of cars and cdrs that will pick 7 from each of the
; following lists:
; (1 3 (5 7) 9)
(define A (list 1 3 (list 5 7) 9))
(car (cdr (car (cdr (cdr a)))))
; ((7))
(define B (list (list 7)))
(car (car B))
; (1 (2 (3 (4 (5 (6 7))))))
(define C (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
(car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr C))))))))))))
;-- 2.26
; Suppose we define x and y to be two lists:
(define x (list 1 2 3))
(define y (list 4 5 6))
; What result is printed by the interpreter in response to evaluating each of
; the following expressions:
(append x y)
; (1 2 3 4 5 6)
(cons x y)
; ((1 2 3) 4 5 6)
(list x y)
; ((1 2 3)(4 5 6))
;-- 2.27
(define (deep-reverse li)
(cond ((null? li) li)
(else (append (deep-reverse (cdr li))
(list (if (pair? (car li))
(deep-reverse (car li))
(car li)))))))
; Test:
(define x (list (list 1 2) (list 3 (list 4 5))))
(deep-reverse x)
;-- 2.28
(define (fringe node)
(if (pair? node)
(append (fringe (car node))
(fringe (cdr node)))
(if (null? node)
'()
(list node))))
; Test:
(define x (list (list 1 2) (list 3 4)))
(fringe x)
; (1 2 3 4)
(fringe (list x x))
; (1 2 3 4 1 2 3 4)
;-- 2.29
(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) (car (cdr mobile)))
(define (branch-length branch) (car branch))
(define (branch-structure branch) (car (cdr branch)))
; b.
(define (branch-weight branch)
(let ((sub (branch-structure branch)))
(if (structure-is-mobile? sub)
(total-weight sub)
sub)))
(define (total-weight mobile)
(+ (branch-weight (left-branch mobile))
(branch-weight (right-branch submobile))))
; c.
(define (balanced? mobile)
(= (branch-weight (left-branch mobile))
(branch-weight (right-branch mobile))))
; d.
; Tests:
(left-branch (make-mobile 2 3))
(right-branch (make-mobile 2 3))
(branch-length (make-branch 4 5))
(branch-structure (make-branch 4 5))
;-- 2.30
(define (square-tree tree)
(cond ((null? tree) nil)
((not (pair? tree)) (* tree tree))
(else (cons (square-tree (car tree))
(square-tree (cdr tree))))))
; With map:
(define (square-tree-map tree)
(map (lambda (x)
(cond ((null? x) nil)
((not (pair? x)) (* x x))
(else (square-tree-map x))))
tree))
; Tests:
(define my-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)))
(square-tree my-tree)
(square-tree-map my-tree)
;-- 2.31
(define (tree-map function tree)
(cond ((null? tree) nil)
((not (pair? tree)) (function tree))
(else (cons (tree-map function (car tree))
(tree-map function (cdr tree))))))
;-- 2.32
(define (subsets s)
(if (null? s)
(list nil)
(let ((rest (subsets (cdr s))))
(append rest
(map (lambda (x) (cons (car s) x))
rest)))))
; Test:
(subsets (list 1 2 3))
; NB: doesn't seem to work well on sisc-scheme.
;-- 2.33
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (map p sequence)
(accumulate (lambda (x y) (cons (p x) y))
nil
sequence))
(define (append seq1 seq2)
(accumulate cons
seq2
seq1))
(define (length sequence)
(accumulate (lambda (x y) (+ 1 y))
0
sequence))
;-- 2.34
(define (horner-eval x coefficient-sequence)
(accumulate (lambda (this-coeff higher-terms) (+ (* x higher-terms)
this-coeff))
0
coefficient-sequence))
; Test:
(horner-eval 2 (list 1 3 0 5 0 1))
; => 79
;-- 2.35
(define (count-leaves t)
(accumulate +
0
(map (lambda (node)
(if (pair? node) (count-leaves node) 1))
t)))
; Test:
(count-leaves (list (list 1 2 3) (list (list 1 2) (list 2)) 2 3 (list 1 2)))
; => 10
;-- 2.36
(define (accumulate-n op init seqs)
(if (null? (car seqs))
nil
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
; Test:
(define listoflist (list (list 1 2 3)
(list 4 5 6)
(list 7 8 9)
(list 10 11 12)))
(accumulate-n + 0 listoflist)
; => (22 26 30)
;-- 2.37
(define (dot-product v w)
(accumulate + 0 (map * v w)))
(define (matrix-*-vector m v)
(map (lambda (x) (dot-product x v))
m))
(define (transpose mat)
(accumulate-n cons
'()
mat))
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map (lambda (x) (matrix-*-vector cols x))
m)))
; Tests:
(define matrix (list (list 1 2 3 4) (list 4 5 6 6) (list 6 7 8 9)))
(define identity-vector (list 1 1 1 1))
(define double-vector (list 2 2 2 2))
(matrix-*-vector matrix identity-vector)
; => (10 21 30)
(matrix-*-vector matrix double-vector)
; => (20 42 60)
(transpose matrix)
; => ((1 4 6) (2 5 7) (3 6 8) (4 6 9))
(matrix-*-matrix matrix matrix)
; => ((27 33 39 43) (60 75 90 100) (82 103 124 138))
;-- 2.38
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
; What are the values of:
(fold-right / 1 (list 1 2 3))
; 3/2
(fold-left / 1 (list 1 2 3))
; 1/6
(fold-right list nil (list 1 2 3))
; (3 (2 (1 ())))
(fold-left list nil (list 1 2 3))
; (((() 1) 2) 3)
; Give a property that op should satisfy to guarantee that fold-right and
; fold-left will produce the same values for any sequence.
; Let's take a (list 1 2 3) and fold it:
; Fold-right => (op 3 (op 2 (op 1 nil))) Ex. (3 * ( 2 * (1)))
; Fold-left => (op (op (op nil 1) 2) 3) Ex. (((1)*2)*3)
; To me it looks like commutativity. However, others point at associativity
; instead. To investigate.
; Commutativity: https://secure.wikimedia.org/wikipedia/en/wiki/Commutativity
; Associativity: https://secure.wikimedia.org/wikipedia/en/wiki/Associativity
;-- 2.39
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
(define (reverse sequence)
(fold-right (lambda (item rest) (append rest (list item)))
nil
sequence))
(define (reverse sequence)
(fold-left (lambda (item rest) (cons rest item))
nil
sequence))
;-- 2.40
; Env:
(define (enumerate-interval a b)
(if (> a b)
nil
(append (list a) (enumerate-interval (+ a 1) b))))
(define (filter predicate sequence)
(cond ((null? sequence) nil)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define nil '())
(define (prime? x)
(define (test divisor)
(cond ((> (* divisor divisor) x) #t)
((= 0 (remainder x divisor)) #f)
(else (test (+ divisor 1)))))
(test 2))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
(define (prime-sum? pair)
(prime? (+ (car pair) (cadr pair))))
(define (make-pair-sum pair)
(list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
(define (prime-sum-pairs n)
(map make-pair-sum
(filter prime-sum?
(flatmap
(lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))))
(define (unique-pairs n)
(flatmap (lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))
(define (prime-sum-pairs n)
(map make-pair-sum
(filter prime-sum? (unique-pairs n))))
;-- 2.41
; Write a procedure to find all ordered triples of distinct positive integers
; i, j, and k less than or equal to a given integer n that sum to a given
; integer s.
(define (ordered-triples n s)
(filter (lambda (triple) (= (fold-left + 0 triple) s))
(flatmap (lambda (i)
(flatmap (lambda (j)
(map (lambda (k) (list i j k))
(enumerate-interval 1 j)))
(enumerate-interval 1 i)))
(enumerate-interval 1 n))))
;-- 2.42
; Env:
(define nil '())
(define (enumerate-interval a b)
(if (> a b)
nil
(append (list a) (enumerate-interval (+ a 1) b))))
(define (filter predicate sequence)
(cond ((null? sequence) nil)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
; Skeleton of the function to implement:
(define (queens board-size)
(define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
; Helper functions:
(define empty-board '())
(define (adjoin-position new-row k rest-of-queens)
(append (list (cons k new-row)) rest-of-queens))
(define (same-line queen-a queen-b) ; Coordinates are (x,y) pairs. If the y is
; the same for both queens, they are on the
; same line.
(= (cdr queen-a) (cdr queen-b)))
(define (same-diagonal queen-a queen-b) ; Two queens are on the same diagonal
; if their horizontal distance is equal
; to their vertical distance
(= (- (car queen-a) (car queen-b))
(abs (- (cdr queen-a) (cdr queen-b)))))
(define (safe? k positions)
(define (safe-iter queen-pos other-queens)
(if (null? other-queens)
#t
(let ((qtt (car other-queens))) ;qtt = queen to test
(cond ((same-line queen-pos qtt) #f) ; Same line
((same-diagonal queen-pos qtt) #f) ; Diagonal
(else (safe-iter queen-pos (cdr other-queens)))))))
(safe-iter (car positions) (cdr positions)))
;-- 2.43
; Way longer, Louis is not skilled.
;-- 2.44
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter (beside smaller smaller)))))
;-- 2.45
(define (right-split painter n)
(if (= n 0)
painter
(let ((smaller (right-split painter (- n 1))))
(beside painter (below smaller smaller)))))
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter (beside smaller smaller)))))
; Right-split and up-split can be expressed as instances of a general splitting
; operation. Define a procedure split with the property that evaluating
; (define right-split (split beside below))
; (define up-split (split below beside))
; produces procedures right-split and up-split with the same behaviors as the
; ones already defined.
(define (split first-transform second-transform)
(define (new-split painter n)
(if (= n 0)
painter
(let ((smaller (new-split painter (- n 1))))
(first-transform painter (second-transform smaller smaller)))))
(lambda (painter n) (new-split painter n)))
; A cleverer version that avoids having to name the lambda in order to recurse,
; from the scheme wiki:
(define (split first-transform second-transform)
(lambda (painter n)
(if (= n 0)
painter
(let ((smaller ((split first-transform second-transform)
painter
(- n 1))))
(first-transform painter (second-transform smaller smaller))))))
;-- 2.46
(define (make-vect x y)
(cons x y))
(define (xcor-vect vect)
(car vect))
(define (ycor-vect vect)
(cdr vect))
(define (add-vect v1 v2)
(make-vect (+ (xcor-vect v1) (xcor-vect v2))
(+ (ycor-vect v1) (ycor-vect v2))))
(define (sub-vect v1 v2)
(make-vect (- (xcor-vect v1) (xcor-vect v2))
(- (ycor-vect v1) (ycor-vect v2))))
(define (scale-vect s vect)
(make-vect (* s (xcor-vect vect))
(* s (ycor-vect vect))))
;-- 2.45
(define (make-frame origin edge1 edge2)
(list origin edge1 edge2))
; Accessors:
(define (origin frame)
(car frame))
(define (edge1 frame)
(car (cdr frame)))
(define (edge2 frame)
(car (cdr (cdr frame))))
(define (make-frame origin edge1 edge2)
(cons origin (cons edge1 edge2)))
; Accessors:
(define (origin frame)
(car frame))
(define (edge1 frame)
(car (cdr frame)))
(define (edge2 frame)
(cdr (cdr frame)))
; The next exercises aren't that interesting.
;-- 2.53
(list 'a 'b 'c)
; (a b c)
(list (list 'george))
; ((george))
(cdr '((x1 x2) (y1 y2)))
; ((y1 y2))
(cadr '((x1 x2) (y1 y2)))
; (y1 y2)
(pair? (car '(a short list)))
; false
(memq 'red '((red shoes) (blue socks)))
; false
(memq 'red '(red shoes blue socks))
; (red shoes blue socks)
;-- 2.54
(define (equal? a b)
(if (and (pair? a) (pair? b)) ; two pairs : we test deeper
(and (equal? (car a) (car b))
(equal? (cdr a) (cdr b)))
(eq? a b))) ; everything else is handled by eq?
;-- 2.55
(car ''abracadabra)
<=> (car '(quote abracadabra))
<=> (car ('quote 'abracadabra))
<=> 'quote
; i.e. the symbol 'quote
;-- 2.56
; Functions given:
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum a1 a2) (list '+ a1 a2)) ; Naive implementation; will be
; replaced afterwards
(define (make-product m1 m2) (list '* m1 m2)) ; Same
(define (sum? x)
(and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s) (caddr s))
(define (product? x)
(and (pair? x) (eq? (car x) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (caddr p))
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
; The question itself:
(define (exponentiation? x)
(and (pair? x) (eq? (car x) '** )))
(define base cadr) ; No need to copy the argument
(define exponent caddr)
(define (make-exponentiation base exponent)
(cond ((=number? base 1) 1)
((=number? exponent 0) 1)
((=number? exponent 1) base)
((and (number? base) (number? exponent)) (expt base exponent))
(else (list '** base exponent))))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
((exponentiation? exp)
(make-product (make-product (exponent exp)
(make-exponentiation (base exp)
(if (number? (exponent exp))
(- (exponent exp) 1)
(list '- (exponent exp) '1))))
(deriv (base exp) var)))
(else
(error "unknown expression type -- DERIV" exp))))
; Test cases:
(deriv '(** 5 6) '2)
; 0
(deriv '(** x 1) 'x)
; 1
(deriv '(** 1 x) 'x)
; 0
(deriv '(** x 5) 'x)
; (* 5 (** x 4))
(deriv '(** x y) 'x)
; (* y (** x (- y 1)))
;-- 2.57
(define (addend s) (cadr s)) ; Does not change
(define (augend s)
(if (null? (cdddr s)) ; Means the addition is just two terms long
(caddr s) ; The term itself
(append '(+) (cddr s)))) ; A new addition comprised of the next terms
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
((sum? a2) (make-sum a1 (make-sum (addend a2) (augend a2))))
(else (list '+ a1 a2))))
(define (multiplier p) (cadr p))
(define (multiplicand p)
(if (null? (cdddr p))
(caddr p)
(append '(*) (cddr p))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((product? m2) (make-product m1 (make-product (multiplier m2)
(multiplicand m2))))
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
; Test:
(deriv '(* x y (+ x 3)) 'x)
; (+ (* x y) (* y (+ x 3)))
;-- 2.58
; a.
(define (sum? x)
(and (pair? x) (pair? (cdr x)) (eq? (cadr x) '+)))
(define addend car)
(define augend caddr)
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list a1 '+ a2))))
(define (product? x)
(and (pair? x) (pair? (cdr x)) (eq? (cadr x) '*)))
(define multiplier car)
(define multiplicand caddr)
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list m1 '* m2))))
; Test:
(deriv '(x + (3 * (x + (y + 2)))) 'x)
; 4
; b.
; It looks long and complicated - kept in stock for a long winter night.
;-- 2.59
; Functions given:
(define (element-of-set? x set)
(cond ((null? set) #f) ; "false" and "true" replaced by their Scheme
; equivalent for convenience
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
; Union:
(define (union-set set1 set2)
(cond ((null? set1) set2) ; We'll add elements of set1 to set2 (given they're
; not already present in set2)
((element-of-set? (car set1) set2)
(union-set (cdr set1) set2))
(else (cons (car set1)
(union-set (cdr set1) set2)))))
; Test:
(define s1 (list 1 2 3 4 5))
(define s2 (list 5 6 7 8))
(intersection-set s1 s2)
; (5)
(union-set s1 s2)
; (1 2 3 4 5 6 7 8)
;-- 2.60
; element-of-set?: doesn't need to change
(define adjoin-set cons) ; No need to check for duplicates
; intersection-set: doesn't change either. It will destroy the duplicates.
(define (union-set set1 set2)
(append set1 set2))
; Test:
(union-set s1 s3)
; (1 2 3 4 5 5 5 5 5)
(intersection-set s1 s3)
; (5)
; Efficiency: by eliminating the need to walk the list, adjoin is now O(1)
; instead of O(n).
; union becomes O(n) instead of O(n²)
;-- 2.61
; Functions given:
(define (element-of-set? x set)
(cond ((null? set) false)
((= x (car set)) true)
((< x (car set)) false)
(else (element-of-set? x (cdr set)))))
(define (intersection-set set1 set2)
(if (or (null? set1) (null? set2))
'()
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1
(intersection-set (cdr set1)
(cdr set2))))
((< x1 x2)
(intersection-set (cdr set1) set2))
((< x2 x1)
(intersection-set set1 (cdr set2)))))))
; Answer:
(define (adjoin-set x set)
(cond ((or (null? set) (< x (car set))) (cons x set))
((= x (car set)) set)
(else (cons (car set) (adjoin-set x (cdr set))))))
; Test:
(define s4 (list 1 2 3 5 6))
(adjoin-set 4 s4)
; (1 2 3 4 5 6)
(adjoin-set 9 s4)
; (1 2 3 5 6 9)
;-- 2.62
(define (union-set set1 set2)
(if (null? set1)
set2
(let ((x1 (car set1)) (x2 (car set2)))
(cond ((= x1 x2)
(cons x1 (union-set (cdr set1) (cdr set2))))
((< x1 x2)
(cons x1 (union-set (cdr set1) set2)))
((< x2 x1)
(cons x2 (union-set set1 (cdr set2))))))))
; This implementation is O(n) because each iteration selects an item from
; either set1 or set2 and cons it (an O(1) operation). There are n iterations
; at most, n being the length of set1 + the length of set2, hence an O(n) total
; complexity.
; Test:
(define s1 (list 1 2 3 4 5))
(define s2 (list 5 6 7 8))
(union-set s1 s2)
; (1 2 3 4 5 6 7 8)
;-- 2.63
; Tree functions:
(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x set)
(cond ((null? set) #f)
((= x (entry set)) #t)
((< x (entry set))
(element-of-set? x (left-branch set)))
((> x (entry set))
(element-of-set? x (right-branch set)))))
(define (adjoin-set x set)
(cond ((null? set) (make-tree x '() '()))
((= x (entry set)) set)
((< x (entry set))
(make-tree (entry set)
(adjoin-set x (left-branch set))
(right-branch set)))
((> x (entry set))
(make-tree (entry set)
(left-branch set)
(adjoin-set x (right-branch set))))))
; a.
; Do the two procedures produce the same result for every tree?
; Yes. To test:
(define t1 (list 7 (list 3 (list 1 '() '()) (list 5 '() '())) (list 9 '() (list 11 '() '()))))
(define t2 (list 3 (list 1 '() '()) (list 7 (list 5 '() '()) (list 9 '() (list 11 '() '())))))
(define t3 (list 5 (list 3 (list 1 '() '()) '()) (list 9 (list 7 '() '()) (list 11 '() '()))))
; If not, how do the results differ? What lists do the two procedures produce
; for the trees in figure 2.16?
; Both tree->list algorithm will print (1 3 5 7 9 11) for the three trees.
; b.
; They're O(n)
;-- 2.64
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts)
right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree this-entry left-tree right-tree)
remaining-elts))))))))
; a.
; Partial-tree splits the list given in two parts of equal size (modulo 1).
; Both halves are submitted to partial-tree through recursion. The recursive
; procedures will yield a pair made of the subtree and the list of elements
; that didn't make it into said subtree. By splitting the process between right
; and left hands, we will ensure that we have a correctly balanced tree. The
; stop condition for partial-tree is asking a tree made of 0 elements, who will
; yield a pair made of an empty list and the list of items.
; Finally, these halves are assembled by a make-tree between the value at the
; middle of the list (strictly speaking the leftmost of the right half) and the
; left and right trees computed beforehand.
; This only works with ordered lists containing no duplicates.
; Tree given for (1 3 5 7 9 11):
; 5
; / \
; 1 9
; \ / \
; 3 7 11
; b.
; Basically O(n).