問題2.83 – SICP(計算機プログラムの構造と解釈)その93

問題2.83

汎用 raise 演算を定義する。

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

整数(scheme-number をそのまま使う)にraise 演算を組み込む。

(define (install-scheme-number-package)
...
  (put 'raise '(scheme-number)
       (lambda (x) (make-rational x 1)))
  'done)

有理数に raise 演算を組み込む。

(define (install-rational-package)
...
  (define (raise-rat x)
    (make-real (/ (* (numer x) 1.0) (denom x))))
...
  (put 'raise '(rational)
       (lambda (x) (raise-rat x)))
  'done)

実数に raise 演算を組み込む。

;; 実数算術演算パッケージ
(define (install-real-package)
  (define (tag x)
    (attach-tag 'real x))
  (put 'add '(real real)
       (lambda (x y) (tag (+ x y))))
  (put 'sub '(real real)
       (lambda (x y) (tag (- x y))))
  (put 'mul '(real real)
       (lambda (x y) (tag (* x y))))
  (put 'div '(real real)
       (lambda (x y) (tag (/ x y))))
  (put 'equ? '(real real)
       (lambda (x y) (= x y)))
  (put '=zero? '(real)
       (lambda (x) (= x 0.0)))
  (put 'make 'real
       (lambda (x) (tag x)))
  (put 'raise '(real)
       (lambda (x) (make-complex-from-real-imag x 0)))
  'done)

(define (make-real n)
  ((get 'make 'real) n))

(install-real-package)

実行結果

(raise 1)
gosh> (rational 1 . 1)
(raise (make-rational 1 2))
gosh> 0.5
(raise (make-real 1.5))
gosh> (complex rectangular 1.5 . 0)

(define i 2)
(raise i)
gosh> (rational 2 . 1)
(raise (raise i))
gosh> (real . 2.0)
(raise (raise (raise i)))
gosh> (complex rectangular 2.0 . 0)
(raise (raise (raise (raise i))))
gosh> *** ERROR: No method for these types (raise (complex))

Stack Trace:
_______________________________________
gosh>
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»