2.1.1有理数の算術演算、問題2.1 – SICP(計算機プログラムの構造と解釈)その25

2.1.1 有理数の算術演算

cons(construct)、car(Contents of Address part of Register)、cdr(Contents of Decrement part of Register)によって対(pair)を作り有理数を表現する。

(define x (cons 1 2))
(car x)
1
(cdr x)
2
(define (add-rat x y)
  (make-rat (+ (* (numer x) (denom y))
               (* (numer y) (denom x)))
            (* (denom x) (denom y))))

(define (sub-rat x y)
  (make-rat (- (* (numer x) (denom y))
               (* (numer y) (denom x)))
            (* (denom x) (denom y))))

(define (mul-rat x y)
  (make-rat (* (numer x) (numer y))
            (* (denom x) (denom y))))

(define (div-rat x y)
  (make-rat (* (numer x) (denom y))
            (* (denom x) (numer y))))

(define (equal-rat? x y)
  (= (* (numer x) (denom y))
     (* (numer y) (denom x))))

(define (make-rat n d) (cons n d))

(define (numer x) (car x))

(define (denom x) (cdr x))

(define (print-rat x)
  (display (numer x))
  (display "/")
  (display (denom x))
  (newline))

(define one-half (make-rat 1 2))
(print-rat one-half)
gosh> 1/2

(define one-third (make-rat 1 3))
(print-rat one-third)
gosh> 1/3

(print-rat (add-rat one-half one-third))
gosh> 5/6

(print-rat (sub-rat one-half one-third))
gosh> 1/6

(print-rat (mul-rat one-half one-third))
gosh> 1/6

(print-rat (div-rat one-half one-third))
gosh> 3/2

(print-rat (add-rat one-third one-third))
gosh> 6/9

問題2.1

正負両方の引数を扱う改良版 make-rat

(define (make-rat n d)
  (let ((g (gcd (abs n) (abs d))))
       (let ((g-n (/ n g))
             (g-d (/ d g)))
            (if (< d 0)
                (cons (- g-n) (- g-d))
                (cons g-n g-d)))))

(define one-third (make-rat 1 -3))
(print-rat (add-rat one-third one-third))
gosh> -2/3

(print-rat (mul-rat one-third one-third))
gosh> 1/9

(print-rat (mul-rat one-half one-third))
gosh> -1/6
計算機プログラムの構造と解釈
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
«
»