Tuesday, June 16, 2009

section-2.5.1, Ex-2.77-2.80

Ex-2.77
(magnitude z)
(apply-generic 'magnitude z)
(apply (get 'magnitude '(complex)) (list (contents z)))
Now let say content of z is z1 wihch is a complex number in polar notation and
(magnitude polar-z)
(apply-generic 'magnitude polar-z)
(apply (get 'magnitude '(polar)) (list (contents polar-z)))
This will find the concrete magnitude procedure to get magnitude of a complex number in polar representation. apply-generic is called two times as we have two level of abstraction. Number->Complex->Polar(or Rectangular).

Ex-2.78
(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 tagged datum -- TYPE-TAG" datum))))

(define (contents datum)
(cond
((number? datum) datum)
((pair? datum) (cdr datum))
(else (error "Bad tagged datum -- CONTENTS" datum))))

Ex-2.79
(define (equ? x y)
(apply-generic 'equ? x y))

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

(define (equ-rational-number? x y)
(and (= (numer x) (numer y))
(= (denom x) (denom y))))
(put 'equ? '(rational rational) equ-rational-number?)

(define (equ-complex-number? x y)
(and (= (real-part x) (real-part y))
(= (imag-part x) (imag-part y))))
(put 'equ? '(complex complex) equ-complex-number?)

Ex-2.80
(define (=zero? x)
(apply-generic '=zero? x))

(put '=zero? '(scheme-numer)
(lambda (x) (= x 0)))

(put '=zero? '(rational)
(lambda (x) (= (numer x) 0)))

(put '=zero? '(complex)
(lambda (x) (and
(= (real-part x) 0)
(= (imag-part x) 0))))

No comments:

Post a Comment