forked from twcamper/sicp-kindle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
book-Z-H-18.html
1757 lines (1397 loc) · 93.9 KB
/
book-Z-H-18.html
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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http:https://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<!-- Generated from TeX source by tex2page, v 4o,
(c) Dorai Sitaram, http:https://www.cs.rice.edu/~dorai/tex2page -->
<head>
<meta name="generator" content="HTML Tidy for Linux (vers 7 December 2008), see www.w3.org" />
<title>Structure and Interpretation of Computer Programs</title>
<link href="book-Z-C.css" title="default" rel="stylesheet" type="text/css" />
<meta name="robots" content="noindex,follow" />
</head>
<body>
<mbp:pagebreak />
<p><a name="%_sec_2.5"></a></p>
<h2><a href="book-Z-H-4.html#%_toc_%_sec_2.5">2.5 Systems with
Generic Operations</a></h2>
<p><a name="%_idx_2496"></a>In the previous section, we saw how
to design systems in which data objects can be represented in
more than one way. The key idea is to link the code that
specifies the data operations to the several representations by
means of generic interface procedures. Now we will see how to use
this same idea not only to define operations that are generic
over different representations but also to define operations that
are generic over different kinds of arguments. We have already
seen several different packages of arithmetic operations: the
primitive arithmetic (<tt>+</tt>, <tt>-</tt>, <tt>*</tt>,
<tt>/</tt>) built into our language, the rational-number
arithmetic (<tt>add-rat</tt>, <tt>sub-rat</tt>, <tt>mul-rat</tt>,
<tt>div-rat</tt>) of section <a href="book-Z-H-14.html#%_sec_2.1.1">2.1.1</a>, and the complex-number
arithmetic that we implemented in section <a href="book-Z-H-17.html#%_sec_2.4.3">2.4.3</a>. We will now use
data-directed techniques to construct a package of arithmetic
operations that incorporates all the arithmetic packages we have
already constructed.</p>
<p>Figure <a href="#%_fig_2.23">2.23</a> shows the structure
of the system we shall build. Notice the <a name="%_idx_2498"></a>abstraction barriers. From the perspective of
someone using ``numbers,'' there is a single procedure
<tt>add</tt> that operates on whatever numbers are supplied.
<tt>Add</tt> is part of a generic interface that allows the
separate ordinary-arithmetic, rational-arithmetic, and
complex-arithmetic packages to be accessed uniformly by programs
that use numbers. Any individual arithmetic package (such as the
complex package) may itself be accessed through generic
procedures (such as <tt>add-complex</tt>) that combine packages
designed for different representations (such as rectangular and
polar). Moreover, the structure of the system is additive, so
that one can design the individual arithmetic packages separately
and combine them to produce a generic arithmetic system. <a name="%_fig_2.23"></a></p>
<div align="left">
<div align="left">
<b>Figure 2.23:</b> Generic arithmetic system.
</div>
<table width="100%">
<tr>
<td><img src="ch2-Z-G-64.gif" border="0" /></td>
</tr>
<tr>
<td><a name="%_idx_2500"></a></td>
</tr>
</table>
</div>
<p><a name="%_sec_2.5.1"></a></p>
<h3><a href="book-Z-H-4.html#%_toc_%_sec_2.5.1">2.5.1 Generic
Arithmetic Operations</a></h3>
<p><a name="%_idx_2502"></a> The task of designing generic
arithmetic operations is analogous to that of designing the
generic complex-number operations. We would like, for instance,
to have a generic addition procedure <tt>add</tt> that acts like
ordinary primitive addition <tt>+</tt> on ordinary numbers, like
<tt>add-rat</tt> on rational numbers, and like
<tt>add-complex</tt> on complex numbers. We can implement
<tt>add</tt>, and the other generic arithmetic operations, by
following the same strategy we used in section <a href="book-Z-H-17.html#%_sec_2.4.3">2.4.3</a> to implement the generic
selectors for complex numbers. We will attach a type tag to each
kind of number and cause the generic procedure to dispatch to an
appropriate package according to the data type of its
arguments.</p>
<p>The generic arithmetic procedures are defined as follows:</p>
<p><tt><a name="%_idx_2504"></a>(define (add x y) (apply-generic 'add x y))<br />
<a name="%_idx_2506"></a>(define (sub x y) (apply-generic 'sub x y))<br />
<a name="%_idx_2508"></a>(define (mul x y) (apply-generic 'mul x y))<br />
<a name="%_idx_2510"></a>(define (div x y) (apply-generic 'div x y))<br />
</tt></p>
<p><a name="%_idx_2512"></a><a name="%_idx_2514"></a>We begin by
installing a package for handling <em>ordinary</em> numbers, that
is, the primitive numbers of our language. We will tag these with
the symbol <tt>scheme-number</tt>. The arithmetic operations in
this package are the primitive arithmetic procedures (so there is
no need to define extra procedures to handle the untagged
numbers). Since these operations each take two arguments, they
are installed in the table keyed by the list <tt>(scheme-number
scheme-number)</tt>: <a name="%_idx_2516"></a><a name="%_idx_2518"></a></p>
<p><tt><a name="%_idx_2520"></a>(define (install-scheme-number-package)<br />
(define (tag x)<br />
(attach-tag 'scheme-number x)) <br />
(put 'add '(scheme-number scheme-number)<br />
(lambda (x y) (tag (+ x y))))<br />
(put 'sub '(scheme-number scheme-number)<br />
(lambda (x y) (tag (- x y))))<br />
(put 'mul '(scheme-number scheme-number)<br />
(lambda (x y) (tag (* x y))))<br />
(put 'div '(scheme-number scheme-number)<br />
(lambda (x y) (tag (/ x y))))<br />
(put 'make 'scheme-number<br />
(lambda (x) (tag x)))<br />
'done)<br /></tt></p>
<p>Users of the Scheme-number package will create (tagged)
ordinary numbers by means of the procedure:</p>
<p><tt><a name="%_idx_2522"></a>(define (make-scheme-number n)<br />
((get 'make 'scheme-number) n))<br /></tt></p>
<p>Now that the framework of the generic arithmetic system is in
place, we can readily include new kinds of numbers. Here is a
package that performs rational arithmetic. Notice that, as a
benefit of additivity, we can use without modification the
rational-number code from section <a href="book-Z-H-14.html#%_sec_2.1.1">2.1.1</a> as the internal
procedures in the package: <a name="%_idx_2524"></a><a name="%_idx_2526"></a><a name="%_idx_2528"></a></p>
<p><tt><a name="%_idx_2530"></a>(define (install-rational-package)<br />
<em>;; internal procedures</em><br />
(define (numer x) (car x))<br />
(define (denom x) (cdr x))<br />
(define (make-rat n d)<br />
(let ((g (gcd n d)))<br />
(cons (/ n g) (/ d g))))<br />
(define (add-rat x y)<br />
(make-rat (+ (* (numer x) (denom y))<br />
(* (numer y) (denom x)))<br />
(* (denom x) (denom y))))<br />
(define (sub-rat x y)<br />
(make-rat (- (* (numer x) (denom y))<br />
(* (numer y) (denom x)))<br />
(* (denom x) (denom y))))<br />
(define (mul-rat x y)<br />
(make-rat (* (numer x) (numer y))<br />
(* (denom x) (denom y))))<br />
(define (div-rat x y)<br />
(make-rat (* (numer x) (denom y))<br />
(* (denom x) (numer y))))<br />
<em>;; interface to rest of the system</em><br />
(define (tag x) (attach-tag 'rational x))<br />
(put 'add '(rational rational)<br />
(lambda (x y) (tag (add-rat x y))))<br />
(put 'sub '(rational rational)<br />
(lambda (x y) (tag (sub-rat x y))))<br />
(put 'mul '(rational rational)<br />
(lambda (x y) (tag (mul-rat x y))))<br />
(put 'div '(rational rational)<br />
(lambda (x y) (tag (div-rat x y))))<br />
<br />
(put 'make 'rational<br />
(lambda (n d) (tag (make-rat n d))))<br />
'done)<br />
<a name="%_idx_2532"></a>(define (make-rational n d)<br />
((get 'make 'rational) n d))<br /></tt></p>
<p>We can install a similar package to handle complex numbers,
using the tag <tt>complex</tt>. In creating the package, we
extract from the table the operations
<tt>make-from-real-imag</tt> and <tt>make-from-mag-ang</tt> that
were defined by the rectangular and polar packages. <a name="%_idx_2534"></a>Additivity permits us to use, as the internal
operations, the same <tt>add-complex</tt>, <tt>sub-complex</tt>,
<tt>mul-complex</tt>, and <tt>div-complex</tt> procedures from
section <a href="book-Z-H-17.html#%_sec_2.4.1">2.4.1</a>.
<a name="%_idx_2536"></a><a name="%_idx_2538"></a><a name="%_idx_2540"></a></p>
<p><tt><a name="%_idx_2542"></a>(define (install-complex-package)<br />
<em>;; imported procedures from rectangular and polar packages</em><br />
(define (make-from-real-imag x y)<br />
((get 'make-from-real-imag 'rectangular) x y))<br />
(define (make-from-mag-ang r a)<br />
((get 'make-from-mag-ang 'polar) r a))<br />
<em>;; internal procedures</em><br />
(define (add-complex z1 z2)<br />
(make-from-real-imag (+ (real-part z1) (real-part z2))<br />
(+ (imag-part z1) (imag-part z2))))<br />
(define (sub-complex z1 z2)<br />
(make-from-real-imag (- (real-part z1) (real-part z2))<br />
(- (imag-part z1) (imag-part z2))))<br />
(define (mul-complex z1 z2)<br />
(make-from-mag-ang (* (magnitude z1) (magnitude z2))<br />
(+ (angle z1) (angle z2))))<br />
(define (div-complex z1 z2)<br />
(make-from-mag-ang (/ (magnitude z1) (magnitude z2))<br />
(- (angle z1) (angle z2))))<br />
<em>;; interface to rest of the system</em><br />
(define (tag z) (attach-tag 'complex z))<br />
(put 'add '(complex complex)<br />
(lambda (z1 z2) (tag (add-complex z1 z2))))<br />
(put 'sub '(complex complex)<br />
(lambda (z1 z2) (tag (sub-complex z1 z2))))<br />
(put 'mul '(complex complex)<br />
(lambda (z1 z2) (tag (mul-complex z1 z2))))<br />
(put 'div '(complex complex)<br />
(lambda (z1 z2) (tag (div-complex z1 z2))))<br />
(put 'make-from-real-imag 'complex<br />
(lambda (x y) (tag (make-from-real-imag x y))))<br />
(put 'make-from-mag-ang 'complex<br />
(lambda (r a) (tag (make-from-mag-ang r a))))<br />
'done)<br /></tt></p>
<p>Programs outside the complex-number package can construct
complex numbers either from real and imaginary parts or from
magnitudes and angles. Notice how the underlying procedures,
originally defined in the rectangular and polar packages, are
exported to the complex package, and exported from there to the
outside world.</p>
<p><tt><a name="%_idx_2544"></a>(define (make-complex-from-real-imag x y)<br />
((get 'make-from-real-imag 'complex) x y))<br />
<a name="%_idx_2546"></a>(define (make-complex-from-mag-ang r a)<br />
((get 'make-from-mag-ang 'complex) r a))<br />
</tt></p>
<p><a name="%_idx_2548"></a>What we have here is a two-level tag
system. A typical complex number, such as 3 + 4<em>i</em> in
rectangular form, would be represented as shown in
figure <a href="#%_fig_2.24">2.24</a>. The outer tag
(<tt>complex</tt>) is used to direct the number to the complex
package. Once within the complex package, the next tag
(<tt>rectangular</tt>) is used to direct the number to the
rectangular package. In a large and complicated system there
might be many levels, each interfaced with the next by means of
generic operations. As a data object is passed ``downward,'' the
outer tag that is used to direct it to the appropriate package is
stripped off (by applying <tt>contents</tt>) and the next level
of tag (if any) becomes visible to be used for further
dispatching.</p>
<p><a name="%_fig_2.24"></a></p>
<div align="left">
<div align="left">
<b>Figure 2.24:</b> Representation of 3 +
4<em>i</em> in rectangular form.
</div>
<table width="100%">
<tr>
<td><img src="ch2-Z-G-65.gif" border="0" /></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<p>In the above packages, we used <tt>add-rat</tt>,
<tt>add-complex</tt>, and the other arithmetic procedures exactly
as originally written. Once these definitions are internal to
different installation procedures, however, they no longer need
names that are distinct from each other: we could simply name
them <tt>add</tt>, <tt>sub</tt>, <tt>mul</tt>, and <tt>div</tt>
in both packages.</p>
<p><a name="%_thm_2.77"></a> <b>Exercise
2.77.</b> Louis Reasoner tries to evaluate the
expression <tt>(magnitude z)</tt> where <tt>z</tt> is the object
shown in figure <a href="#%_fig_2.24">2.24</a>. To his
surprise, instead of the answer 5 he gets an error message from
<tt>apply-generic</tt>, saying there is no method for the
operation <tt>magnitude</tt> on the types <tt>(complex)</tt>. He
shows this interaction to Alyssa P. Hacker, who says ``The
problem is that the complex-number selectors were never defined
for <tt>complex</tt> numbers, just for <tt>polar</tt> and
<tt>rectangular</tt> numbers. All you have to do to make this
work is add the following to the <tt>complex</tt> package:''</p>
<p><tt>(put 'real-part '(complex) real-part)<br />
(put 'imag-part '(complex) imag-part)<br />
(put 'magnitude '(complex) magnitude)<br />
(put 'angle '(complex) angle)<br /></tt></p>
<p>Describe in detail why this works. As an example, trace
through all the procedures called in evaluating the expression
<tt>(magnitude z)</tt> where <tt>z</tt> is the object shown in
figure <a href="#%_fig_2.24">2.24</a>. In particular, how
many times is <tt>apply-generic</tt> invoked? What procedure is
dispatched to in each case?</p>
<p><a name="%_thm_2.78"></a> <b>Exercise
2.78.</b> <a name="%_idx_2550"></a><a name="%_idx_2552"></a><a name="%_idx_2554"></a><a name="%_idx_2556"></a><a name="%_idx_2558"></a><a name="%_idx_2560"></a><a name="%_idx_2562"></a>The internal procedures
in the <tt>scheme-number</tt> package are essentially nothing
more than calls to the primitive procedures <tt>+</tt>,
<tt>-</tt>, etc. It was not possible to use the primitives of the
language directly because our type-tag system requires that each
data object have a type attached to it. In fact, however, all
Lisp implementations do have a type system, which they use
internally. Primitive predicates such as <tt>symbol?</tt> and
<tt>number?</tt> determine whether data objects have particular
types. Modify the definitions of <tt>type-tag</tt>,
<tt>contents</tt>, and <tt>attach-tag</tt> from
section <a href="book-Z-H-17.html#%_sec_2.4.2">2.4.2</a> so
that our generic system takes advantage of Scheme's internal type
system. That is to say, the system should work as before except
that ordinary numbers should be represented simply as Scheme
numbers rather than as pairs whose <tt>car</tt> is the symbol
<tt>scheme-number</tt>.</p>
<p><a name="%_thm_2.79"></a> <b>Exercise
2.79.</b> <a name="%_idx_2564"></a><a name="%_idx_2566"></a>Define a generic equality predicate
<tt>equ?</tt> that tests the equality of two numbers, and install
it in the generic arithmetic package. This operation should work
for ordinary numbers, rational numbers, and complex numbers.</p>
<p><a name="%_thm_2.80"></a> <b>Exercise
2.80.</b> <a name="%_idx_2568"></a><a name="%_idx_2570"></a>Define a generic predicate <tt>=zero?</tt> that
tests if its argument is zero, and install it in the generic
arithmetic package. This operation should work for ordinary
numbers, rational numbers, and complex numbers.</p>
<p><a name="%_sec_2.5.2"></a></p>
<h3><a href="book-Z-H-4.html#%_toc_%_sec_2.5.2">2.5.2 Combining
Data of Different Types</a></h3>
<p>We have seen how to define a unified arithmetic system that
encompasses ordinary numbers, complex numbers, rational numbers,
and any other type of number we might decide to invent, but we
have ignored an important issue. The operations we have defined
so far treat the different data types as being completely
independent. Thus, there are separate packages for adding, say,
two ordinary numbers, or two complex numbers. What we have not
yet considered is the fact that it is meaningful to define
operations that cross the type boundaries, such as the addition
of a complex number to an ordinary number. We have gone to great
pains to introduce barriers between parts of our programs so that
they can be developed and understood separately. We would like to
introduce the cross-type operations in some carefully controlled
way, so that we can support them without seriously violating our
module boundaries.</p>
<p><a name="%_idx_2572"></a><a name="%_idx_2574"></a><a name="%_idx_2576"></a>One way to handle cross-type operations is to
design a different procedure for each possible combination of
types for which the operation is valid. For example, we could
extend the complex-number package so that it provides a procedure
for adding complex numbers to ordinary numbers and installs this
in the table using the tag <tt>(complex
scheme-number)</tt>:<a href="#footnote_Temp_283" name="call_footnote_Temp_283" id="call_footnote_Temp_283"><sup><small>49</small></sup></a></p>
<p>
<tt><em>;; to be included in the complex package</em><br />
<a name="%_idx_2578"></a>(define (add-complex-to-schemenum z x)<br />
(make-from-real-imag (+ (real-part z) x)<br />
(imag-part z)))<br />
(put 'add '(complex scheme-number)<br />
(lambda (z x) (tag (add-complex-to-schemenum z x))))<br />
</tt></p>
<p>This technique works, but it is cumbersome. With such a
system, the cost of introducing a new type is not just the
construction of the package of procedures for that type but also
the construction and installation of the procedures that
implement the cross-type operations. This can easily be much more
code than is needed to define the operations on the type itself.
The method also undermines our ability to combine separate
packages additively, or least to limit the extent to which the
implementors of the individual packages need to take account of
other packages. For instance, in the example above, it seems
reasonable that handling mixed operations on complex numbers and
ordinary numbers should be the responsibility of the
complex-number package. Combining rational numbers and complex
numbers, however, might be done by the complex package, by the
rational package, or by some third package that uses operations
extracted from these two packages. Formulating coherent policies
on the division of responsibility among packages can be an
overwhelming task in designing systems with many packages and
many cross-type operations.</p>
<p><a name="%_sec_Temp_284"></a></p>
<h4><a href="book-Z-H-4.html#%_toc_%_sec_Temp_284">Coercion</a></h4>
<p><a name="%_idx_2580"></a> In the general situation of
completely unrelated operations acting on completely unrelated
types, implementing explicit cross-type operations, cumbersome
though it may be, is the best that one can hope for. Fortunately,
we can usually do better by taking advantage of additional
structure that may be latent in our type system. Often the
different data types are not completely independent, and there
may be ways by which objects of one type may be viewed as being
of another type. This process is called <em>coercion</em>. For
example, if we are asked to arithmetically combine an ordinary
number with a complex number, we can view the ordinary number as
a complex number whose imaginary part is zero. This transforms
the problem to that of combining two complex numbers, which can
be handled in the ordinary way by the complex-arithmetic
package.</p>
<p><a name="%_idx_2582"></a>In general, we can implement this
idea by designing coercion procedures that transform an object of
one type into an equivalent object of another type. Here is a
typical coercion procedure, which transforms a given ordinary
number to a complex number with that real part and zero imaginary
part:</p>
<p><tt><a name="%_idx_2584"></a>(define (scheme-number->complex n)<br />
(make-complex-from-real-imag (contents n) 0))<br />
</tt></p>
<p><a name="%_idx_2586"></a><a name="%_idx_2588"></a>We install
these coercion procedures in a special coercion table, indexed
under the names of the two types:</p>
<p>
<tt>(put-coercion 'scheme-number 'complex scheme-number->complex)<br />
</tt></p>
<p>(We assume that there are <tt>put-coercion</tt> and
<tt>get-coercion</tt> procedures available for manipulating this
table.) Generally some of the slots in the table will be empty,
because it is not generally possible to coerce an arbitrary data
object of each type into all other types. For example, there is
no way to coerce an arbitrary complex number to an ordinary
number, so there will be no general
<tt>complex->scheme-number</tt> procedure included in the
table.</p>
<p>Once the coercion table has been set up, we can handle
coercion in a uniform manner by modifying the
<tt>apply-generic</tt> procedure of section <a href="book-Z-H-17.html#%_sec_2.4.3">2.4.3</a>. When asked to apply an
operation, we first check whether the operation is defined for
the arguments' types, just as before. If so, we dispatch to the
procedure found in the operation-and-type table. Otherwise, we
try coercion. For simplicity, we consider only the case where
there are two arguments.<a href="#footnote_Temp_285" name="call_footnote_Temp_285" id="call_footnote_Temp_285"><sup><small>50</small></sup></a> We
check the coercion table to see if objects of the first type can
be coerced to the second type. If so, we coerce the first
argument and try the operation again. If objects of the first
type cannot in general be coerced to the second type, we try the
coercion the other way around to see if there is a way to coerce
the second argument to the type of the first argument. Finally,
if there is no known way to coerce either type to the other type,
we give up. Here is the procedure:</p>
<p><tt><a name="%_idx_2590"></a>(define (apply-generic op . args)<br />
(let ((type-tags (map type-tag args)))<br />
(let ((proc (get op type-tags)))<br />
(if proc<br />
(apply proc (map contents args))<br />
(if (= (length args) 2)<br />
(let ((type1 (car type-tags))<br />
(type2 (cadr type-tags))<br />
(a1 (car args))<br />
(a2 (cadr args)))<br />
(let ((t1->t2 (get-coercion type1 type2))<br />
(t2->t1 (get-coercion type2 type1)))<br />
(cond (t1->t2<br />
(apply-generic op (t1->t2 a1) a2))<br />
(t2->t1<br />
(apply-generic op a1 (t2->t1 a2)))<br />
(else<br />
(error "No method for these types"<br />
(list op type-tags))))))<br />
(error "No method for these types"<br />
(list op type-tags)))))))<br />
</tt></p>
<p>This coercion scheme has many advantages over the method of
defining explicit cross-type operations, as outlined above.
Although we still need to write coercion procedures to relate the
types (possibly <em>n</em><sup>2</sup> procedures for a system
with <em>n</em> types), we need to write only one procedure for
each pair of types rather than a different procedure for each
collection of types and each generic operation.<a href="#footnote_Temp_286" name="call_footnote_Temp_286" id="call_footnote_Temp_286"><sup><small>51</small></sup></a> What we
are counting on here is the fact that the appropriate
transformation between types depends only on the types
themselves, not on the operation to be applied.</p>
<p>On the other hand, there may be applications for which our
coercion scheme is not general enough. Even when neither of the
objects to be combined can be converted to the type of the other
it may still be possible to perform the operation by converting
both objects to a third type. In order to deal with such
complexity and still preserve modularity in our programs, it is
usually necessary to build systems that take advantage of still
further structure in the relations among types, as we discuss
next.</p>
<p><a name="%_sec_Temp_287"></a></p>
<h4><a href="book-Z-H-4.html#%_toc_%_sec_Temp_287">Hierarchies of
types</a></h4>
<p><a name="%_idx_2592"></a><a name="%_idx_2594"></a> The
coercion scheme presented above relied on the existence of
natural relations between pairs of types. Often there is more
``global'' structure in how the different types relate to each
other. For instance, suppose we are building a generic arithmetic
system to handle integers, rational numbers, real numbers, and
complex numbers. In such a system, it is quite natural to regard
an integer as a special kind of rational number, which is in turn
a special kind of real number, which is in turn a special kind of
complex number. What we actually have is a so-called
<em>hierarchy of types</em>, in which, for example, integers are
a <a name="%_idx_2596"></a><a name="%_idx_2598"></a><em>subtype</em> of rational numbers (i.e., any
operation that can be applied to a rational number can
automatically be applied to an integer). Conversely, we say that
rational numbers form a <a name="%_idx_2600"></a><a name="%_idx_2602"></a><em>supertype</em> of integers. The particular
hierarchy we have here is of a very simple kind, in which each
type has at most one supertype and at most one subtype. Such a
structure, called a <em>tower</em>, is illustrated in
figure <a href="#%_fig_2.25">2.25</a>.</p>
<p><a name="%_fig_2.25"></a></p>
<div align="left">
<div align="left">
<b>Figure 2.25:</b> A tower of types.
</div>
<table width="100%">
<tr>
<td><img src="ch2-Z-G-66.gif" border="0" /></td>
</tr>
<tr>
<td><a name="%_idx_2604"></a><a name="%_idx_2606"></a></td>
</tr>
</table>
</div>
<p>If we have a tower structure, then we can greatly simplify the
problem of adding a new type to the hierarchy, for we need only
specify how the new type is embedded in the next supertype above
it and how it is the supertype of the type below it. For example,
if we want to add an integer to a complex number, we need not
explicitly define a special coercion procedure
<tt>integer->complex</tt>. Instead, we define how an integer
can be transformed into a rational number, how a rational number
is transformed into a real number, and how a real number is
transformed into a complex number. We then allow the system to
transform the integer into a complex number through these steps
and then add the two complex numbers.</p>
<p><a name="%_idx_2608"></a><a name="%_idx_2610"></a>We can
redesign our <tt>apply-generic</tt> procedure in the following
way: For each type, we need to supply a <tt>raise</tt> procedure,
which ``raises'' objects of that type one level in the tower.
Then when the system is required to operate on objects of
different types it can successively raise the lower types until
all the objects are at the same level in the tower.
(Exercises <a href="#%_thm_2.83">2.83</a> and <a href="#%_thm_2.84">2.84</a> concern the details of implementing such a
strategy.)</p>
<p>Another advantage of a tower is that we can easily implement
the notion that every type ``inherits'' all operations defined on
a supertype. For instance, if we do not supply a special
procedure for finding the real part of an integer, we should
nevertheless expect that <tt>real-part</tt> will be defined for
integers by virtue of the fact that integers are a subtype of
complex numbers. In a tower, we can arrange for this to happen in
a uniform way by modifying <tt>apply-generic</tt>. If the
required operation is not directly defined for the type of the
object given, we raise the object to its supertype and try again.
We thus crawl up the tower, transforming our argument as we go,
until we either find a level at which the desired operation can
be performed or hit the top (in which case we give up).</p>
<p><a name="%_idx_2612"></a>Yet another advantage of a tower over
a more general hierarchy is that it gives us a simple way to
``lower'' a data object to the simplest representation. For
example, if we add 2 + 3<em>i</em> to 4 - 3<em>i</em>, it would
be nice to obtain the answer as the integer 6 rather than as the
complex number 6 + 0<em>i</em>. Exercise <a href="#%_thm_2.85">2.85</a> discusses a way to implement such a
lowering operation. (The trick is that we need a general way to
distinguish those objects that can be lowered, such as 6 +
0<em>i</em>, from those that cannot, such as 6 +
2<em>i</em>.)</p>
<p><a name="%_fig_2.26"></a></p>
<div align="left">
<div align="left">
<b>Figure 2.26:</b> Relations among types of
geometric figures.
</div>
<table width="100%">
<tr>
<td><img src="ch2-Z-G-67.gif" border="0" /></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</div>
<p><a name="%_sec_Temp_288"></a></p>
<h4><a href="book-Z-H-4.html#%_toc_%_sec_Temp_288">Inadequacies
of hierarchies</a></h4>
<p><a name="%_idx_2614"></a> If the data types in our system can
be naturally arranged in a tower, this greatly simplifies the
problems of dealing with generic operations on different types,
as we have seen. Unfortunately, this is usually not the case.
Figure <a href="#%_fig_2.26">2.26</a> illustrates a more
complex arrangement of mixed types, this one showing relations
among different types of geometric figures. We see that, in
general, <a name="%_idx_2616"></a><a name="%_idx_2618"></a><a name="%_idx_2620"></a>a type may have more
than one subtype. Triangles and quadrilaterals, for instance, are
both subtypes of polygons. In addition, a type may have more than
one supertype. For example, an isosceles right triangle may be
regarded either as an isosceles triangle or as a right triangle.
This multiple-supertypes issue is particularly thorny, since it
means that there is no unique way to ``raise'' a type in the
hierarchy. Finding the ``correct'' supertype in which to apply an
operation to an object may involve considerable searching through
the entire type network on the part of a procedure such as
<tt>apply-generic</tt>. Since there generally are multiple
subtypes for a type, there is a similar problem in coercing a
value ``down'' the type hierarchy. Dealing with large numbers of
interrelated types while still preserving modularity in the
design of large systems is very difficult, and is an area of much
current research.<a href="#footnote_Temp_289" name="call_footnote_Temp_289" id="call_footnote_Temp_289"><sup><small>52</small></sup></a></p>
<p><a name="%_thm_2.81"></a> <b>Exercise
2.81.</b> <a name="%_idx_2626"></a>Louis Reasoner has
noticed that <tt>apply-generic</tt> may try to coerce the
arguments to each other's type even if they already have the same
type. Therefore, he reasons, we need to put procedures in the
coercion table to "coerce" arguments of each type to their own
type. For example, in addition to the
<tt>scheme-number->complex</tt> coercion shown above, he would
do:</p>
<p><tt><a name="%_idx_2628"></a>(define (scheme-number->scheme-number n) n)<br />
<a name="%_idx_2630"></a>(define (complex->complex z) z)<br />
(put-coercion 'scheme-number 'scheme-number<br />
scheme-number->scheme-number)<br />
(put-coercion 'complex 'complex complex->complex)<br />
</tt></p>
<p>a. With Louis's coercion procedures installed, what happens if
<tt>apply-generic</tt> is called with two arguments of type
<tt>scheme-number</tt> or two arguments of type <tt>complex</tt>
for an operation that is not found in the table for those types?
For example, assume that we've defined a generic exponentiation
operation:</p>
<p>
<tt>(define (exp x y) (apply-generic 'exp x y))<br />
</tt></p>
<p>and have put a procedure for exponentiation in the
Scheme-number package but not in any other package:</p>
<p>
<tt><em>;; following added to Scheme-number package</em><br />
(put 'exp '(scheme-number scheme-number)<br />
(lambda (x y) (tag (expt x y)))) <em>; using primitive <tt>expt</tt></em><br />
</tt></p>
<p>What happens if we call <tt>exp</tt> with two complex numbers
as arguments?</p>
<p>b. Is Louis correct that something had to be done about
coercion with arguments of the same type, or does
<tt>apply-generic</tt> work correctly as is?</p>
<p>c. Modify <tt>apply-generic</tt> so that it doesn't try
coercion if the two arguments have the same type.</p>
<p><a name="%_thm_2.82"></a> <b>Exercise
2.82.</b> <a name="%_idx_2632"></a>Show how to
generalize <tt>apply-generic</tt> to handle coercion in the
general case of multiple arguments. One strategy is to attempt to
coerce all the arguments to the type of the first argument, then
to the type of the second argument, and so on. Give an example of
a situation where this strategy (and likewise the two-argument
version given above) is not sufficiently general. (Hint: Consider
the case where there are some suitable mixed-type operations
present in the table that will not be tried.)</p>
<p><a name="%_thm_2.83"></a> <b>Exercise
2.83.</b> <a name="%_idx_2634"></a>Suppose you are
designing a generic arithmetic system for dealing with the tower
of types shown in figure <a href="#%_fig_2.25">2.25</a>:
integer, rational, real, complex. For each type (except complex),
design a procedure that raises objects of that type one level in
the tower. Show how to install a generic <tt>raise</tt> operation
that will work for each type (except complex).</p>
<p><a name="%_thm_2.84"></a> <b>Exercise
2.84.</b> <a name="%_idx_2636"></a>Using the
<tt>raise</tt> operation of exercise <a href="#%_thm_2.83">2.83</a>, modify the <tt>apply-generic</tt>
procedure so that it coerces its arguments to have the same type
by the method of successive raising, as discussed in this
section. You will need to devise a way to test which of two types
is higher in the tower. Do this in a manner that is
``compatible'' with the rest of the system and will not lead to
problems in adding new levels to the tower.</p>
<p><a name="%_thm_2.85"></a> <b>Exercise
2.85.</b> <a name="%_idx_2638"></a><a name="%_idx_2640"></a>This section mentioned a method for
``simplifying'' a data object by lowering it in the tower of
types as far as possible. Design a procedure <tt>drop</tt> that
accomplishes this for the tower described in
exercise <a href="#%_thm_2.83">2.83</a>. The key is to
decide, in some general way, whether an object can be lowered.
For example, the complex number 1.5 + 0<em>i</em> can be lowered
as far as <tt>real</tt>, the complex number 1 + 0<em>i</em> can
be lowered as far as <tt>integer</tt>, and the complex number 2 +
3<em>i</em> cannot be lowered at all. Here is a plan for
determining whether an object can be lowered: Begin by defining a
generic operation <tt>project</tt> that ``pushes'' an object down
in the tower. For example, projecting a complex number would
involve throwing away the imaginary part. Then a number can be
dropped if, when we <tt>project</tt> it and <tt>raise</tt> the
result back to the type we started with, we end up with something
equal to what we started with. Show how to implement this idea in
detail, by writing a <tt>drop</tt> procedure that drops an object
as far as possible. You will need to design the various
projection operations<a href="#footnote_Temp_295" name="call_footnote_Temp_295" id="call_footnote_Temp_295"><sup><small>53</small></sup></a> and
install <tt>project</tt> as a generic operation in the system.
You will also need to make use of a generic equality predicate,
such as described in exercise <a href="#%_thm_2.79">2.79</a>. Finally, use <tt>drop</tt> to rewrite
<tt>apply-generic</tt> from exercise <a href="#%_thm_2.84">2.84</a> so that it ``simplifies'' its answers.</p>
<p><a name="%_thm_2.86"></a> <b>Exercise
2.86.</b> Suppose we want to handle complex numbers
whose real parts, imaginary parts, magnitudes, and angles can be
either ordinary numbers, rational numbers, or other numbers we
might wish to add to the system. Describe and implement the
changes to the system needed to accommodate this. You will have
to define operations such as <tt>sine</tt> and <tt>cosine</tt>
that are generic over ordinary numbers and rational numbers.</p>
<p><a name="%_sec_2.5.3"></a></p>
<h3><a href="book-Z-H-4.html#%_toc_%_sec_2.5.3">2.5.3 Example:
Symbolic Algebra</a></h3>
<p><a name="%_idx_2646"></a> The manipulation of symbolic
algebraic expressions is a complex process that illustrates many
of the hardest problems that occur in the design of large-scale
systems. An algebraic expression, in <a name="%_idx_2648"></a>general, can be viewed as a hierarchical
structure, a tree of operators applied to operands. We can
construct algebraic expressions by starting with a set of
primitive objects, such as constants and variables, and combining
these by means of algebraic operators, such as addition and
multiplication. As in other languages, we form abstractions that
enable us to refer to compound objects in simple terms. Typical
abstractions in symbolic algebra are ideas such as linear
combination, polynomial, rational function, or trigonometric
function. We can regard these as compound ``types,'' which are
often useful for directing the processing of expressions. For
example, we could describe the expression</p>
<div align="left"><img src="ch2-Z-G-68.gif" border="0" /></div>
<p>as a polynomial in <em>x</em> with coefficients that are
trigonometric functions of polynomials in <em>y</em> whose
coefficients are integers.</p>
<p>We will not attempt to develop a complete
algebraic-manipulation system here. Such systems are exceedingly
complex programs, embodying deep algebraic knowledge and elegant
algorithms. What we will do is look at a simple but important
part of algebraic manipulation: the arithmetic of polynomials. We
will illustrate the kinds of decisions the designer of such a
system faces, and how to apply the ideas of abstract data and
generic operations to help organize this effort.</p>
<p><a name="%_sec_Temp_297"></a></p>
<h4><a href="book-Z-H-4.html#%_toc_%_sec_Temp_297">Arithmetic on
polynomials</a></h4>
<p><a name="%_idx_2650"></a><a name="%_idx_2652"></a> Our first
task in designing a system for performing arithmetic on
polynomials is to decide just what a polynomial is. Polynomials
are normally defined relative to certain variables (the <a name="%_idx_2654"></a><a name="%_idx_2656"></a><em>indeterminates</em>
of the polynomial). For simplicity, we will restrict ourselves to
polynomials having just one indeterminate (<a name="%_idx_2658"></a><a name="%_idx_2660"></a><em>univariate
polynomials</em>).<a href="#footnote_Temp_298" name="call_footnote_Temp_298" id="call_footnote_Temp_298"><sup><small>54</small></sup></a> We will
define a polynomial to be a sum of terms, each of which is either
a coefficient, a power of the indeterminate, or a product of a
coefficient and a power of the indeterminate. A coefficient is
defined as an algebraic expression that is not dependent upon the
indeterminate of the polynomial. For example,</p>
<div align="left"><img src="ch2-Z-G-69.gif" border="0" /></div>
<p>is a simple polynomial in <em>x</em>, and</p>
<div align="left"><img src="ch2-Z-G-70.gif" border="0" /></div>
<p>is a polynomial in <em>x</em> whose coefficients are
polynomials in <em>y</em>.</p>
<p>Already we are skirting some thorny issues. Is the first of
these polynomials the same as the polynomial
5<em>y</em><sup>2</sup> + 3<em>y</em> + 7, or not? A reasonable
answer might be ``yes, if we are considering a polynomial purely
as a mathematical function, but no, if we are considering a
polynomial to be a syntactic form.'' The second polynomial is
algebraically equivalent to a polynomial in <em>y</em> whose
coefficients are polynomials in <em>x</em>. Should our system
recognize this, or not? Furthermore, there are other ways to
represent a polynomial -- for example, as a product of factors,
or (for a univariate polynomial) as the set of roots, or as a
listing of the values of the polynomial at a specified set of
points.<a href="#footnote_Temp_299" name="call_footnote_Temp_299" id="call_footnote_Temp_299"><sup><small>55</small></sup></a> We
can finesse these questions by deciding that in our
algebraic-manipulation system a ``polynomial'' will be a
particular syntactic form, not its underlying mathematical
meaning.</p>
<p>Now we must consider how to go about doing arithmetic on
polynomials. In this simple system, we will consider only
addition and multiplication. Moreover, we will insist that two
polynomials to be combined must have the same indeterminate.</p>
<p>We will approach the design of our system by following the
familiar discipline of data abstraction. We will represent
polynomials using a data structure called a <a name="%_idx_2664"></a><em>poly</em>, which consists of a variable and
a <a name="%_idx_2666"></a>collection of terms. We assume that we
have selectors <tt>variable</tt> and <tt>term-list</tt> that
extract those parts from a poly and a constructor
<tt>make-poly</tt> that assembles a poly from a given variable
and a term list. A variable will be just a symbol, so we can use
the <a name="%_idx_2668"></a><tt>same-variable?</tt> procedure of
section <a href="book-Z-H-16.html#%_sec_2.3.2">2.3.2</a> to
compare variables. <a name="%_idx_2670"></a><a name="%_idx_2672"></a>The following procedures define addition and
multiplication of polys:</p>
<p><tt><a name="%_idx_2674"></a>(define (add-poly p1 p2)<br />
(if (same-variable? (variable p1) (variable p2))<br />
(make-poly (variable p1)<br />
(add-terms (term-list p1)<br />
(term-list p2)))<br />
(error "Polys not in same var -- ADD-POLY"<br />
(list p1 p2))))<br />
<a name="%_idx_2676"></a>(define (mul-poly p1 p2)<br />
(if (same-variable? (variable p1) (variable p2))<br />
(make-poly (variable p1)<br />
(mul-terms (term-list p1)<br />
(term-list p2)))<br />
(error "Polys not in same var -- MUL-POLY"<br />
(list p1 p2))))<br />
</tt></p>
<p>To incorporate polynomials into our generic arithmetic system,
we need to supply them with type tags. We'll use the tag
<tt>polynomial</tt>, and install appropriate operations on tagged
polynomials in the operation table. We'll embed all our code in
an installation procedure for the polynomial package, similar to
the ones in section <a href="#%_sec_2.5.1">2.5.1</a>:
<a name="%_idx_2678"></a><a name="%_idx_2680"></a><a name="%_idx_2682"></a></p>
<p><tt><a name="%_idx_2684"></a><a name="%_idx_2686"></a><a name="%_idx_2688"></a><a name="%_idx_2690"></a>(define (install-polynomial-package)<br />
<em>;; internal procedures</em><br />
<em>;; representation of poly</em><br />
(define (make-poly variable term-list)<br />
(cons variable term-list))<br />
(define (variable p) (car p))<br />
(define (term-list p) (cdr p))<br />
<<em>procedures <tt>same-variable?</tt> and <tt>variable?</tt> from section <a href="book-Z-H-16.html#%_sec_2.3.2">2.3.2</a></em>><br />
<em>;; representation of terms and term lists</em><br />
<<em>procedures <tt>adjoin-term </tt>...</em><tt>coeff</tt></tt> from text below><br />
<br />
<em>;; continued on next page</em><br />
<br />
(define (add-poly p1 p2) <tt>...</tt>)<br />
<<em>procedures used by <tt>add-poly</tt></em>><br />
(define (mul-poly p1 p2) <tt>...</tt>)<br />
<<em>procedures used by <tt>mul-poly</tt></em>><br />
<em>;; interface to rest of the system</em><br />
(define (tag p) (attach-tag 'polynomial p))<br />
(put 'add '(polynomial polynomial) <br />
(lambda (p1 p2) (tag (add-poly p1 p2))))<br />