(apply-generic 'magnitude '(complex rectangular 3 4)) --> ((get 'magnitude '(complex)) '(rectangular 3 4)) --> (magnitude '(rectangular 3 4)) --> (apply-generic 'magnitude '(rectangular 3 4)) --> ((get 'magnitude '(rectangular)) (3 4)) --> (magnitude (3 4))
(define (attach-tag type-tag contents) (if (number? contents) contents (cons type-tag contents))) (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad taged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad taged datum -- CONTENTS" datum))))
(define (equ? x y) (apply-generic 'equ ? x y)) (put 'equ? '(scheme-number scheme-number) =) (put 'equ? '(rational rational) equ-rat?) (define (equ-rat? x y) (and (= (numer x) (numer y)) (= (denom x) (denom y))) (put 'equ? '(complex complex) equ-complex?) (define (equ-complex? x y) (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))
The tag of the number should be managed separately in the procedures.
(define (=zero? x) (apply-generic '=zero? x)) (put '=zero? 'scheme-number (lambda (x) (= x 0))) (put '=zero? 'rational-number (lambda (x) (= (number x) 0))) (put '=zero? 'complex-number (lambda (x) (= (magnitude x) 0)))