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

問題2.88

符号を反転する手続きを各パッケージに追加する。

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

;;; 整数(integer)演算パッケージ
(define (install-integer-package)
...
  (put 'negative '(integer)
       (lambda (x) (tag (- x))))
...
  'done)

;;; 有理数(rational)演算パッケージ
(define (install-rational-package)
...
  (define (negative-rat x)
    (make-rat (- (numer x)) (denom x)))
...
  (put 'negative '(rational)
       (lambda (x) (tag (negative-rat x))))
...
  'done)

;;; 実数(real)演算パッケージ
(define (install-real-package)
...
  (put 'negative '(real)
       (lambda (x) (tag (- x))))
...
  'done)

;;; 複素数(complex)演算パッケージ
(define (install-complex-package)
...
  (put 'negative '(complex)
       (lambda (z) (tag (make-from-real-imag (negative (real-part z))
                                             (negative (imag-part z))))))
...
  'done)

;;;;;; 多項式(poly)の算術演算
(define (install-polynomial-package)
...
  (define (negative-poly p)
    (make-poly (variable p) (negative-term (term-list p))))

  (define (negative-term L)
    (if (empty-termlist? L)
        (the-empty-termlist)
        (let ((t (first-term L)))
             (adjoin-term
               (make-term (order t) (negative (coeff t)))
               (negative-term (rest-terms L))))))
...
  (put 'negative '(polynomial)
       (lambda (p) (tag (negative-poly p))))
...
  'done)

多項式システムに減算を追加する。

;;;;;; 多項式(poly)の算術演算
(define (install-polynomial-package)
...
  (define (sub-poly p1 p2)
    (if (same-variable? (variable p1) (variable p2))
        (make-poly (variable p1)
                   (add-terms (term-list p1)
                              (negative-term (term-list p2))))
        (error "Polys not in same var -- ADD-POLY" (list p1 p2))))
...
  (put 'sub '(polynomial polynomial)
       (lambda (p1 p2) (tag (sub-poly p1 p2))))
...
  'done)

実行結果

(define p1 (make-polynomial 'x '((3 1) (2 2) (0 1))))
(define p2 (make-polynomial 'x '((3 4) (2 3) (0 1))))
(define p3 (make-polynomial 'x `((1 ,p1) (0 3))))
(define p4 (make-polynomial 'x `((1 ,p2) (0 2))))
(add p1 p2)
gosh> (polynomial x (3 5) (2 5) (0 2))
(mul p1 p2)
gosh> (polynomial x (6 4) (5 11) (4 6) (3 5) (2 5) (0 1))
(sub p1 p2)
gosh> (polynomial x (3 -3) (2 -1))
(add p3 p4)
gosh> (polynomial x (1 (polynomial x (3 5) (2 5) (0 2))) (0 5))
(mul p3 p4)
gosh> (polynomial x (2 (polynomial x (6 4) (5 11) (4 6) (3 5) (2 5) (0 1))) (1 (polynomial x (3 14) (2 13) (0 5))) (0 6))
(sub p3 p4)
gosh> (polynomial x (1 (polynomial x (3 -3) (2 -1))) (0 1))
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»