sicp-2-5-1

Posted on 2015-02-24 21:01:24 +0900 in SICP Lisp

2.77

(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))

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 taged datum -- TYPE-TAG" datum))))

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

2.79

(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.

2.80

(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)))
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | sicp-2-4 »

Hide Comments

comments powered by Disqus