sicp-ex-2.93



<< Previous exercise (2.92) | Index | Next exercise (2.94) >>


woofy

  
  
  
 (define (install-rational-package) 
     ;; internal procuedures 
     (define (numer x) (car x)) 
     (define (denom x) (cdr x)) 
     (define (make-rat n d) (cons n d)) 
     (define (add-rat x y) 
         (make-rat (add (mul (numer x) (denom y)) 
                        (mul (numer y) (demom x))) 
                   (mul (denom x) (demom y)))) 
     (define (sub-rat x y) 
         (make-rat (sub (mul (numer x) (denom y)) 
                        (mul (numer y) (demom x))) 
                   (mul (denom x) (demom y)))) 
     (define (mul-rat x y) 
         (make-rat (mul (numer x) (numer y)) 
                   (mul (denom x) (denom y)))) 
     (define (div-rat x y) 
         (make-rat (mul (numer x) (denom y)) 
                   (mul (denom x) (numer y)))) 
      
     ;; interface to rest of the system 
     ; same as before 
 ) 
  
 (define p1 (make-polynomial 'x '((2 1) (0 1)))) 
 (define p1 (make-polynomial 'x '((3 1) (0 1)))) 
 (define rf (make-rational p2 p1)) 
  
 (add rf rf) 

meteorgan

  
  
 (define (greatest-common-divisor a b) 
   (apply-generic 'greatest-common-divisor a b)) 
  
 ;; add into scheme-number package 
 (put 'greatest-common-divisor '(scheme-number scheme-number) 
      (lambda (a b) (gcd a b))) 
  
 ;; add into polynomial package 
 (define (remainder-terms p1 p2) 
   (cadr (div-terms p1 p2))) 
  
 (define (gcd-terms a b) 
   (if (empty-termlist? b) 
     a 
     (gcd-terms b (remainder-terms a b)))) 
  
 (define (gcd-poly p1 p2) 
   (if (same-varaible? (variable p1) (variable p2)) 
         (make-poly (variable p1) 
                    (gcd-terms (term-list p1) 
                               (term-list p2)) 
         (error "not the same variable -- GCD-POLY" (list p1 p2))))) 
  
 (put 'greatest-common-divisor '(polynomial polynomial) 
          (lambda (a b) (tag (gcd-poly a b))))