# SICP Solutions

### Section - 2.5 - Systems with Generic Operations

#### Exercise 2.84

It is an interesting exercise. I implemented it for raising operation by assuming single rooted hierarchy - or tree shaped hierarchy - so tower shape will automatically work.

Points to note:

• It is easy now to add a new type in the existing system.
• As of now there is following tower implemented in my arithmetic system: rational -> scheme-number -> complex. Note my scheme-number is a real number. I have not implemented the package for only integers. Since the idea is same so I skipped the integer package :). Thus the lowest in my hierarchy is rational and not integer.
• When a new type is added in arithmatic package, the developer of the package needs to tell two things - parent by calling put-parent <child> <parent> and how to raise to parent by calling put-rais <child> <raise-proc>.
• Thus the new type need not to worry about any other type - just mention the parent and how to raise into the parent!
• The current system works if there is no defined operation for the current types. For Eg: Here exp is only defined for ‘scheme-number, but not for rational. When rational-numbers are supplied for exp then the procedure first checks - if this operation is present in rational package. If not it tries to upcast to next type which in this case is ‘scheme-number. Now after upcasting to scheme-number, the exp procedure is found as it is defined there. Thus it is called for the result.
• Suppose even after upcasting to all the super-types - the operation is not found - then it reports error.
• To check if this works with tree - create tree as: scheme-number -> complex, rational -> complex. And to test lets remove sub procedure from the rational package. Then this call (sub (make-number 5) (make-rational 1 5)) should work by upcasting both arguments to complex and then calling sub for the complex package. Note in this case (exp (make-rational 1 2) (make-number -1)) wont work because in the new-hierarchy rational number cannot be upcasted to scheme-number where exp is defined.
• Note that the procedures used inside apply-generic should not be based on apply-generic for eg: raise can not be called using apply-generic because it creates a circular dependency: raise -> apply-generic -> raise …(I happen to make this mistake and later removed raise from apply-generic and moved it to separate table - raise-table).
• I used two new tables - type-table and cast-table - which can be combined also but for simplicity i kept them separate.

Output/Examples: