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

問題2.93

汎用演算を使うように修正した有理数(rational)演算パッケージ。

(define (install-rational-package)
  (define (numer x) (car x))
  (define (denom x) (cdr x))
  (define (make-rat n d)
    (cons n d))

  (define (add-rat x y)
    (make-rat (add (mul (numer x) (denom y))
                 (mul (numer y) (denom x)))
              (mul (denom x) (denom y))))
  (define (sub-rat x y)
    (make-rat (sub (mul (numer x) (denom y))
                 (mul (numer y) (denom x)))
              (mul (denom x) (denom y))))
  (define (mul-rat x y)
    (make-rat (mul (numer x) (numer y))
              (mul (denom x) (denom y))))
  (define (div-rat x y)
    (make-rat (mul (numer x) (denom y))
              (mul (denom x) (numer y))))
  (define (=rat-zero? x)
    (= (numer x) 0))
  (define (rat-equ? x y)
    (if (and (= (numer x) (numer y)) (= (denom x) (denom y)))
        #t
        #f))
  (define (negative-rat x)
    (make-rat (- (numer x)) (denom x)))
  ;;
  (define (tag x) (attach-tag 'rational x))
  (put 'add '(rational rational)
       (lambda (x y) (tag (add-rat x y))))
  (put 'sub '(rational rational)
       (lambda (x y) (tag (sub-rat x y))))
  (put 'mul '(rational rational)
       (lambda (x y) (tag (mul-rat x y))))
  (put 'div '(rational rational)
       (lambda (x y) (tag (div-rat x y))))
  (put '=zero? '(rational)
       (lambda (x) (=rat-zero? x)))
  (put 'make 'rational
       (lambda (n d) (tag (make-rat n d))))
  (put 'equ? '(rational rational)
       (lambda (x y) (rat-equ? x y)))
  (put 'negative '(rational)
       (lambda (x) (tag (negative-rat x))))
  'done)

(install-rational-package)

(define (make-rational n d)
  ((get 'make 'rational) n d))

実行結果

(define p1 (make-polynomial 'x '((2 1) (0 1))))
(define p2 (make-polynomial 'x '((3 1) (0 1))))
(make-rational (make-integer 2) (make-integer 4))
(define rf (make-rational p2 p1))
;(rational (polynomial x (3 1) (0 1)) polynomial x (2 1) (0 1))

(add rf rf)
gosh> (rational (polynomial x (5 2) (3 2) (2 2) (0 2)) polynomial x (4 1) (2 2) (0 1))
(sub rf rf)
gosh> (rational (polynomial x) polynomial x (4 1) (2 2) (0 1))
(mul rf rf)
gosh> (rational (polynomial x (6 1) (3 2) (0 1)) polynomial x (4 1) (2 2) (0 1))
(div rf rf)
gosh> (rational (polynomial x (5 1) (3 1) (2 1) (0 1)) polynomial x (5 1) (3 1) (2 1) (0 1))
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»