sicp每日一題[2.83]

再思即可發表於2024-11-20

Exercise 2.83

Suppose you are designing a generic arithmetic system for dealing with the tower of types shown in Figure 2.25: 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 raise operation that will work for each type (except complex).


這道題挺簡單的,只要在每個包裡用下一級的構造方法生成符合下一級規則的數就行。因為有理數本身就可以直接看成實數,所以我沒有寫有理數到實數和實數到複數的轉換過程,這樣直接在 2.81 的基礎上修改就行了。

(define (raise x) (apply-generic 'raise x))

; interger to rational,在 scheme-number 包新增如下程式碼
(put 'raise '(scheme-number) (lambda (x) make-rational x 1))

; rational to complex,在 rational 包新增如下程式碼
(put 'raise '(rational) (lambda (x) (make-complex-from-real-imag x 0)))

; 如果要實現有理數到實數的轉換,只要將有理數轉換為分子分母相除再乘以 1.0 即可

相關文章