理系学生日記

おまえはいつまで学生気分なのか

忍者TOOLS

問題2-79 (2.5.1 Generic Arithmetic Operations)

汎用性のあるequ?を作ります。
equ?は与えられた2つの数(有理数だったり複素数だったり)が一緒かどうか調べる関数だ!!


rectanglarパッケージにこれ1つずつ追加。

  (define (equ? z1 z2)
    (and (= (real-part z1) (real-part z2))
	 (= (imag-part z1) (imag-part z2))))
  (put 'equ? '(rectangular rectangular)
       (lambda (z1 z2) (equ? z1 z2)))

polarパッケージにこの2つ追加

(define (equ? z1 z2)
    (and (= (magnitude z1) (magnitude z2))
	 (= (angle z1) (angle z2))))
(put 'equ? '(polar polar)
       (lambda (z1 z2) (equ? z1 z2)))

scheme-numberパッケージにはこれ。

(put 'equ? '(scheme-number scheme-number)
       (lambda (x y) (= x y)))

rationalパッケージにはこれ

(define (equ? x y)
    (and (= (numer x)  (numer y))
	 (= (denom x) (denom y))))

とこれ。

(put 'equ? '(rational rational)
       (lambda (z1 z2) (equ? z1 z2)))

んで、complexパッケージにこれ。

(put 'equ? '(complex complex)
       (lambda (z1 z2) (equ? z1 z2)))

やったーできたよ!

(equ? (make-scheme-number 3) (make-scheme-number 3)) ; #t
(equ? (make-scheme-number 4) (make-scheme-number 3)) ; #f
(equ? (make-complex-from-real-imag 1 5) (make-complex-from-real-imag 1 5)) ; #t
(equ? (make-complex-from-real-imag 3 5) (make-complex-from-real-imag 1 5)) ; #f
(equ? (make-complex-from-mag-ang 2 3.14) (make-complex-from-mag-ang 2 3.14)) ; #t
(equ? (make-complex-from-mag-ang 5 3.14) (make-complex-from-mag-ang 2 3.14)) ; #f
(equ? (make-rational 3 5) (make-rational 3 5)) ; #t
(equ? (make-rational 2 4) (make-rational 3 5)) ; #f