Chapter 2, Building Abstractions with Data
Section  2.5  Systems with Generic Operations
Exercise 2.85
Creating â€˜projectionâ€™ is similar to creating â€˜raiseâ€™ operation. Just need to set procedures in the respective packages. â€˜dropâ€™ is simple to implement. But as soon as I put â€˜dropâ€™ in â€˜applygenericâ€™ the trouble started which took me quite some time debugging. Here are the problems that I faced after putting â€˜dropâ€™:
Note: I am using only 3 types in my hierarchy: rational > schemenumber(real number) > â€˜complex. Update: Later, in ex2.88, I have added the integer package too.

Even drop itself stopped working! Not only â€˜applygenericâ€™ but direct calls to â€˜dropâ€™ not working. Reason was â€˜dropâ€™ is using â€˜equ?â€™. When it was called for â€˜complex type the â€˜equ?â€™ calls â€˜equ?â€™ again to compare real and imaginary part. So â€˜realpart is called using
applygeneric
. That means drop is called on the â€˜realpart returned by the procedure. Now our drop, drops this to rationanumber.Thus the â€˜equ of complex number should call â€˜equ of rational numbers to compare the real and imag parts. But it was using=
. So changed this call to call â€˜equ usingapplygeneric
. 
Now since â€˜equ is also using
applygeneric
that meansdrop
is evoked on the result of â€˜equ. Thusdrop
is called on boolean!. And to add to the trouble there was a bug in mytypetag
which is silently ignoring the error when(typetag <boolean>)
or any other nontyped argument is used. This is the reason why I think that static typed languages are better. Well, I fixed thetypetag
and also created a prochastypetag?
anddrop
first checks if that is true only then it tries to drop. 
Now the next problem happens as I try operation
add
to complex numbers. The problem is that now since drop is getting called on â€˜realpart the real and imag part of complex numbers can be rational too! So I can not directly add two complex numbers by adding their real and imag parts. But now, â€˜addâ€™ should be used instead on â€˜+â€™. Thus replaced all the operations +,,*,/ with add,sub,mul, and div. 
Well thats it!
Initially I was thinking that its not a good idea that the procedures that are used by applygeneric
should themselves be invoked using applygeneric(Eg: raise and projection). Because it was causing circular dependency and may go into infinite recursion. Now after implementing this procedure  and as per the requirement of this exercise operation â€˜equ can not be avoided to implement and â€˜equ can not work without applygeneric
 that helped me in understanding that it applygeneric
can also internally use itself as long as we are clear how things are working. In case of drop the recursion stops as drop
drops the type to lasttype possible!
So, I think now raise and projection can also be used with â€˜applygenericâ€™  something that I avoided for the sake of circular dependency. Another thing to wonder here is: Did I evade complexity or enhanced it by creating new table for raise/project operations? I think I should do it only with the old table but this exercise has already taken a lot of time. Probably will try later if I revisit sicp.
So here goes the complete code:
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
#lang sicp
(#%require (only racket/base error))
(#%require (only racket/base makehash))
(#%require (only racket/base hashset!))
(#%require (only racket/base hashref))
(define (drop arg)
(if (hastypetag? arg)
(let ((type (typetag arg)))
(let ((proc (getprojection type)))
(if (not (null? proc))
(let ((projected (proc arg)))
(let ((raised (raisetotype type projected)))
(if ((get 'equ? (list type type)) (contents raised) (contents arg))
(drop projected)
arg
)
)
)
arg
)
)
)
arg
)
)
(define (applygeneric op . args)
(let ((typetags (map typetag args)))
(let ((proc (get op typetags)))
(if (not (null? proc))
(drop (apply proc (map contents args)))
(let ((hassametype
(accumulate
(lambda (a b) (and a b))
#t
(map
(lambda(x) (equal? (car typetags) x))
(cdr typetags)
)
)
))
(let ((highesttype (if hassametype
(getparent (car typetags))
(findhighesttype typetags)
)
))
(if (null? highesttype)
(error "Could not find a suitable ancestor" op args)
(let ((raisedargs (mapuntil
'()
(lambda(arg)
(raisetotype highesttype arg)
)
args
)
))
(if (not (null? raisedargs))
(apply applygeneric op raisedargs)
(error "Error. No suitable raise method found to raise all types into " highesttype " for raising types " typetags)
)
)
)
)
)
)
)
)
)
(define *typetable* (makehash))
(define (putparent type parent)
(let ((alreadyset (hashref *typetable* (list 'parent type) '())))
(if (null? alreadyset)
(hashset! *typetable* (list 'parent type) parent)
(error "Parent already defined for :" type " parent currently *present* is " alreadyset " the passed parent " parent)
)
)
)
(define (getparent type)
(hashref *typetable* (list 'parent type) '())
)
(define (putchild type child)
(let ((alreadyset (hashref *typetable* (list 'child type) '())))
(if (null? alreadyset)
(hashset! *typetable* (list 'child type) child)
(error "Child already defined for :" type " child currently *present* is " alreadyset " the passed child " child)
)
)
)
(define (getchild type)
(hashref *typetable* (list 'child type) '())
)
(define *casttable* (makehash))
(define (putraise type proc)
(let ((alreadyset (hashref *casttable* (list 'raise type) '())))
(if (null? alreadyset)
(hashset! *casttable* (list 'raise type) proc)
(error "Raise is already defined for :" type)
)
)
)
(define (getraise type)
(hashref *casttable* (list 'raise type) '())
)
(define (putprojection type proc)
(let ((alreadyset (hashref *casttable* (list 'project type) '())))
(if (null? alreadyset)
(hashset! *casttable* (list 'project type) proc)
(error "Project is already defined for :" type)
)
)
)
(define (getprojection type)
(hashref *casttable* (list 'project type) '())
)
(define (getancestors type)
(if (null? type)
'()
(cons type (getancestors (getparent type)))
)
)
(define (contains item itemlist)
(foldleft
(lambda(result new)
(or result (equal? item new))
)
#f
itemlist
)
)
(define (findhighesttype typetags)
(let ((ancestorsofeachtype (map getancestors typetags)))
(let ((smallestancestorset
(accumulate (lambda(new remaining)
(if (< (size new) (size remaining))
new
remaining
)
)
(car ancestorsofeachtype)
ancestorsofeachtype
)
))
(define (findtypepresentineachancestors typelist)
(if (null? typelist)
'()
(let ((found (accumulate
(lambda (a b) (and a b))
#t
(map
(lambda(ancestors) (contains (car typelist) ancestors))
ancestorsofeachtype)
)
))
(if found
(car typelist)
(findtypepresentineachancestors (cdr typelist))
)
)
)
)
(findtypepresentineachancestors smallestancestorset)
)
)
)
(define (raisetotype type arg)
(cond ((null? arg) '())
((equal? type (typetag arg)) arg)
(else (let ((proc (getraise (typetag arg))))
(if (null? proc)
'()
(raisetotype type (proc arg))
)
)
)
)
)
(define (mapuntil untilval proc args)
(if (null? args)
'()
(let ((arg (car args)))
(let ((marg (proc arg)))
(if (equal? marg untilval)
'()
(cons marg (mapuntil untilval proc (cdr args)))
)
)
)
)
)
(define (foldleft op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(define (raise n)
((getraise (typetag n)) n)
)
(define (square x) (* x x))
(define *optable* (makehash))
(define (put op type proc)
(hashset! *optable* (list op type) proc)
)
(define (get op type)
(hashref *optable* (list op type) '())
)
(define (attachtag typetag contents)
(if (number? contents)
contents
(cons typetag contents)
)
)
(define (hastypetag? datum)
(cond
((number? datum) #t)
((pair? datum)
(contains (car datum) '(complex rational))
)
(else #f)
)
)
(define (typetag datum)
(cond
((number? datum) 'schemenumber)
((pair? datum) (car datum))
(else (error "Bad tagged datum  TYPETAG" datum))
)
)
(define (contents datum)
(cond ((number? datum) datum)
((pair? datum) (cdr datum))
(error "Bad tagged datum  CONTENTS" datum)
)
)
(define (filter predicate sequence)
(cond ((null? sequence) nil)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (size list)
(if (null? list) 0 (+ 1 (size (cdr list)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))
)
)
(define (installschemenumberpackage)
(define (tag x)
(attachtag 'schemenumber x))
(put 'add '(schemenumber schemenumber)
(lambda (x y) (tag (+ x y))))
(put 'sub '(schemenumber schemenumber)
(lambda (x y) (tag ( x y))))
(put 'mul '(schemenumber schemenumber)
(lambda (x y) (tag (* x y))))
(put 'div '(schemenumber schemenumber)
(lambda (x y) (tag (/ x y))))
(put 'make 'schemenumber
(lambda (x) (tag x)))
;equ?
(put 'equ? '(schemenumber schemenumber) =)
;; following added to Schemenumber package
(put 'exp '(schemenumber schemenumber)
(lambda (x y) (tag (expt x y)))) ; using primitive expt
; raise operation
(putraise 'schemenumber (lambda(x) (makecomplexfromrealimag (contents x) 0)))
; set parent
(putparent 'schemenumber 'complex)
;a simple way to convert from real to rational is by multiplying and dividing by a
; constant but it will only be correct to 4 places of decimal(4 zeroes in 10000)
(define multiplier 10000)
; project operation
(putprojection 'schemenumber (lambda(c) (makerational (floor (* (contents c) multiplier)) multiplier)))
; set child
(putchild 'schemenumber 'rational)
'done
)
(define (makenumber n)
((get 'make 'schemenumber) n)
)
(define (installrationalpackage)
;; internal procedures
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (makerat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (addrat x y)
(makerat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (subrat x y)
(makerat ( (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mulrat x y)
(makerat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (divrat x y)
(makerat (* (numer x) (denom y))
(* (denom x) (numer y))))
;; equ?
(define (equ? x y)
(and (= (numer x) (numer y)) (= (denom x) (denom y))))
;; interface to rest of the system
(define (tag x) (attachtag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (addrat x y))))
; comment this to check the example suggested above for tree structure support
(put 'sub '(rational rational)
(lambda (x y) (tag (subrat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mulrat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (divrat x y))))
(put 'make 'rational
(lambda (n d) (tag (makerat n d))))
(put 'equ? '(rational rational) equ?)
; raise operation
(putraise 'rational (lambda(r) (makenumber (/ (numer (contents r)) (denom (contents r))))))
; set parent
(putparent 'rational 'schemenumber)
; uncomment this and comment above raise to make rational as child of complex instead of number
; (putraise 'rational (lambda(r) (makecomplexfromrealimag (/ (numer (contents r)) (denom (contents r))) 0)))
; uncomment this and comment above raise to make rational as child of complex instead of number
; (putparent 'rational 'complex)
'done
)
(define (makerational n d)
((get 'make 'rational) n d)
)
(define (installcomplexpackage)
;; imported procedures from rectangular and polar packages
(define (makefromrealimag x y)
((get 'makefromrealimag 'rectangular) x y))
(define (makefrommagang r a)
((get 'makefrommagang 'polar) r a))
;; internal procedures
(define (addcomplex z1 z2)
(makefromrealimag (add (applygeneric 'realpart z1) (applygeneric 'realpart z2))
(add (applygeneric 'imagpart z1) (applygeneric 'imagpart z2))))
(define (subcomplex z1 z2)
(makefromrealimag (sub (applygeneric 'realpart z1) (applygeneric 'realpart z2))
(sub (applygeneric 'imagpart z1) (applygeneric 'imagpart z2))))
(define (mulcomplex z1 z2)
(makefrommagang (mul (applygeneric 'magnitude z1) (applygeneric 'magnitude z2))
(add (applygeneric 'angle z1) (applygeneric 'angle z2))))
(define (divcomplex z1 z2)
(makefrommagang (div (applygeneric 'magnitude z1) (applygeneric 'magnitude z2))
(sub (applygeneric 'angle z1) (applygeneric 'angle z2))))
(define (equ? z1 z2)
(and
(applygeneric 'equ? (applygeneric 'realpart z1) (applygeneric 'realpart z2))
(applygeneric 'equ? (applygeneric 'imagpart z1) (applygeneric 'imagpart z2))
)
)
;; interface to rest of the system
(define (tag z) (attachtag 'complex z))
(put 'add '(complex complex)
(lambda (z1 z2) (tag (addcomplex z1 z2))))
(put 'sub '(complex complex)
(lambda (z1 z2) (tag (subcomplex z1 z2))))
(put 'mul '(complex complex)
(lambda (z1 z2) (tag (mulcomplex z1 z2))))
(put 'div '(complex complex)
(lambda (z1 z2) (tag (divcomplex z1 z2))))
(put 'makefromrealimag 'complex
(lambda (x y) (tag (makefromrealimag x y))))
(put 'makefrommagang 'complex
(lambda (r a) (tag (makefrommagang r a))))
(put 'equ? '(complex complex) equ?)
; raise operation is not defined for complex
; parent not defined for complex
; project operation
(putprojection
'complex
(lambda(c)
;note that we can not call applygeneric here because this method is used by drop and drop is used in generic
;thus it can go into a loop
;so need to take care of typetags here only
; c is complex number(includes tag complex) cc is rectangular/angular including the typetag
; Note that, the repurcurssions of drop lead to the point that real and imag can be any number except number
; thus raising it to the real number type (because apart from complex numbers, my understanding is any number can be raised to real number
(let ((cc (contents c)))
(raisetotype 'schemenumber ((get 'realpart (list (typetag cc))) (contents cc)))
)
)
)
; set child
(putchild 'complex 'schemenumber)
'done
)
(define (installrectangularpackage)
;; internal procedures
(define (realpart z) (car z))
(define (imagpart z) (cdr z))
(define (makefromrealimag x y) (cons x y))
(define (magnitude z)
(sqrt (+ (square (realpart z))
(square (imagpart z)))))
(define (angle z)
(atan (imagpart z) (realpart z)))
(define (makefrommagang r a)
(cons (* r (cos a)) (* r (sin a))))
;; interface to the rest of the system
(define (tag x) (attachtag 'rectangular x))
(put 'realpart '(rectangular) realpart)
(put 'imagpart '(rectangular) imagpart)
(put 'magnitude '(rectangular) magnitude)
(put 'angle '(rectangular) angle)
(put 'makefromrealimag 'rectangular
(lambda (x y) (tag (makefromrealimag x y))))
(put 'makefrommagang 'rectangular
(lambda (r a) (tag (makefrommagang r a))))
'done)
(define (installpolarpackage)
;; internal procedures
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (makefrommagang r a) (cons r a))
(define (realpart z)
(* (magnitude z) (cos (angle z))))
(define (imagpart z)
(* (magnitude z) (sin (angle z))))
(define (makefromrealimag x y)
(cons (sqrt (+ (square x) (square y)))
(atan y x)))
;; interface to the rest of the system
(define (tag x) (attachtag 'polar x))
(put 'realpart '(polar) realpart)
(put 'imagpart '(polar) imagpart)
(put 'magnitude '(polar) magnitude)
(put 'angle '(polar) angle)
(put 'makefromrealimag 'polar
(lambda (x y) (tag (makefromrealimag x y))))
(put 'makefrommagang 'polar
(lambda (r a) (tag (makefrommagang r a))))
'done)
(define (makecomplexfromrealimag x y)
((get 'makefromrealimag 'complex) x y))
(define (makecomplexfrommagang r a)
((get 'makefrommagang 'complex) r a))
(define (equ? x y)
(applygeneric 'equ? x y)
)
(define (exp x y) (applygeneric 'exp x y))
(define (add x y) (applygeneric 'add x y))
(define (sub x y) (applygeneric 'sub x y))
(define (mul x y) (applygeneric 'mul x y))
(define (div x y) (applygeneric 'div x y))
(installrectangularpackage)
(installpolarpackage)
(installschemenumberpackage)
(installrationalpackage)
(installcomplexpackage)
Example/Output:
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
> (display (add (makecomplexfromrealimag 2.5 9) (makecomplexfromrealimag 1 9)))
(rational 7.0 . 2.0)
> (findhighesttype (map typetag (list (makenumber 50000) (makecomplexfromrealimag 2 3))))
'complex
> (display (add (makecomplexfromrealimag 2.5 9) (makecomplexfromrealimag 1 9)))
(rational 7.0 . 2.0)
> (display (add (makecomplexfromrealimag 2.5 9) (makecomplexfromrealimag 100 20)))
(complex rectangular (rational 205.0 . 2.0) rational 11 . 1)
> (display (add (makenumber 50000) (makecomplexfromrealimag 2 3)))
(complex rectangular (rational 50002 . 1) rational 3 . 1)
> (display (add (makerational 1 5) (makecomplexfromrealimag 2 3)))
(complex rectangular (rational 11 . 5) rational 3 . 1)
> (exp (makenumber 2) (makenumber 3))
(mcons 'rational (mcons 8 1))
> (display (exp (makenumber 2) (makenumber 3)))
(rational 8 . 1)
> (display (exp (makerational 1 2) (makenumber 1)))
(rational 2 . 1)
> (exp (makerational 1 2) (makenumber 1))
(mcons 'rational (mcons 2 1))
> (display (exp (makecomplexfromrealimag 1 2) (makenumber 3)))
;This error is expected because exp is not defined for complex numbers.
. . Could not find a suitable ancestor exp ((complex rectangular 1 . 2) (complex rectangular 3 . 0
))
> (display (exp (makerational 25 100) (makerational 1 2)))
(rational 1 . 2)
> (display (sub (makerational 7 2) (add (makecomplexfromrealimag 2.5 9) (makecomplexfromrealimag 1 9))))
(rational 0.0 . 1.0)
> (display (mul (makecomplexfromrealimag 2.5 3) (makecomplexfromrealimag 3 4)))
(complex polar 19.525624189766635 . 1.8033532685998055)
>