Приведение аргументов с помощью последовательного повышения


Из SICP:

Упражнения 2.84

Используя поднять операция упражнения 2.83, изменить применение-универсальная процедура, так что это приводит свои аргументы одинаковые типа методом последовательных воспитание, как описано в этом разделе. Вам нужно придумать способ, чтобы проверить какой из двух типов выше в башня. Сделать это таким образом, что `совместимость" с остальными системы и не приведет к проблемам при добавлении новых уровней в башне.

Я написал следующее решение. В частности, обращайте внимание на все-typematch функции и применение-универсальный.

(define (make-all-typematch . args)
  (define (typematch obj1 obj2)
    (cond ((eq? (type-tag obj1) (type-tag obj2)) obj1)
          ((and (not (can-raise? obj1))
                (not (can-raise? obj2))) '())
          ((higher? obj2 obj1)
           (and (can-raise? obj1) 
                (typematch (raise obj1) obj2)))  
          (else (and (can-raise? obj2) 
                     (typematch obj1 (raise obj2))))))
  (define (least-common-type first second . rest)
    (let ((matched-obj (typematch first second)))
      (if (not (null? matched-obj))
          (if (null? rest) 
              (type-tag matched-obj)
              (apply least-common-type (cons matched-obj rest)))
          '())))
  (define (raise-to-type the-type arg)
    (if (eq? (type-tag arg) the-type)
        arg
        (raise-to-type the-type (raise arg))))
  (define (iter result the-type args)
    (if (null? args) 
        result
        (iter (cons (raise-to-type the-type (car args))
                    result)
              the-type
              (cdr args))))
  (let ((lct (apply least-common-type args)))
    (if (null? lct)
        (error "Can't make these objects agree:" args)
        (iter '() lct args))))

(define (apply-generic op . args)
  (define (all-same? head . rest)
    (if (null? rest)
        true
        (and (eq? head (car rest))
             (apply all-same? rest))))
  (let ((type-tags (map type-tag args)))
    (let ((proc (get op type-tags)))
      (if proc
          (apply proc (map contents args))
          (if (and (> (length type-tags) 1)
                   (apply all-same? type-tags))
              (error
               "No method for these types -- APPLY-GENERIC"
               (list op type-tags))
              (apply apply-generic op (apply make-all-typematch args)))))))

(define (add x y) (apply-generic 'add x y))
(define (sub x y) (apply-generic 'sub x y))
(define (mul x y) (apply-generic 'mul x y))
(define (div x y) (apply-generic 'div x y))
(define (equ? x y) (apply-generic 'equ? x y))
(define (=zero? x) (apply-generic '=zero? x))
(define (raise x) (apply-generic 'raise x))
(define (can-raise? x) (if (with-handlers ([exn:fail? (lambda (exn) false)])
                             (raise x))
                           true
                           false))
(define (can-be-raised-to? type x)
  (or (eq? (type-tag x) type)
      (and (can-raise? x)
           (can-be-raised-to? type (raise x)))))
(define (higher? x y) 
  (can-be-raised-to? (type-tag x) y))
(define (square x) (* x x))

(define (attach-tag type-tag contents)
  (if (or (symbol? contents) (number? contents))
      contents
      (cons type-tag contents)))

(define (type-tag datum)
  (cond ((pair? datum) (car datum))
        ((exact? datum) 'scheme-number)
        ((inexact? datum) 'scheme-real)
        ((symbol? datum) 'scheme-symbol)
        (else (error "Bad tagged datum -- TYPE-TAG" datum))))

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

(define fn-registry '())
(define (get op param-types)
  (define (rec entry . rest)
    (define (all-equal a b)
      (if (symbol? a)
          (eq? a b)
          (and (= (length a) (length b))
               (let loop ((x a) (y b))
                 (or (null? x)
                     (and (eq? (car x) (car y))
                          (loop (cdr x) (cdr y))))))))
    (let ((op-entry (car entry))
          (param-types-entry (cadr entry))
          (function-entry (caddr entry)))
      (if (and (eq? op-entry op)
               (all-equal param-types-entry param-types))
          function-entry
          (if (null? rest)
              false
              (apply rec rest)))))
  (apply rec fn-registry))

(define (put op param-types fn)
  (set! fn-registry (cons (list op param-types fn) fn-registry)))

(define (install-scheme-number-package)
  (define (tag x)
    (attach-tag 'scheme-number x))    
  (put 'add '(scheme-number scheme-number)
       (lambda (x y) (tag (+ x y))))
  (put 'sub '(scheme-number scheme-number)
       (lambda (x y) (tag (- x y))))
  (put 'mul '(scheme-number scheme-number)
       (lambda (x y) (tag (* x y))))
  (put 'div '(scheme-number scheme-number)
       (lambda (x y) (tag (/ x y))))
  (put 'make '(scheme-number)
       (lambda (x) (tag x)))
  (put 'equ? '(scheme-number scheme-number) =)
  (put '=zero? '(scheme-number) zero?)
  (put 'raise '(scheme-number) (lambda (x) (if (integer? x) (make-rational x 1) (make-real x))))
  'done)

(define (make-scheme-number n)
  ((get 'make 'scheme-number) n))

(define (install-real-number-package)
  (define (tag x)
    (attach-tag 'scheme-real x))
  (put 'add '(scheme-real scheme-real)
       (lambda (x y) (tag (+ x y))))
  (put 'sub '(scheme-real scheme-real)
       (lambda (x y) (tag (- x y))))
  (put 'mul '(scheme-real scheme-real)
       (lambda (x y) (tag (* x y))))
  (put 'div '(scheme-real scheme-real)
       (lambda (x y) (tag (/ x y))))
  (put 'make '(scheme-real)
       (lambda (x) (tag x)))
  (put 'equ? '(scheme-real scheme-real) =)
  (put '=zero? '(scheme-real) zero?)
  (put 'raise '(scheme-real) (lambda (x) (make-complex-from-real-imag x 0)))
  'done)
(define (make-real n)
  ((get 'make '(scheme-real)) n))

(define (install-rational-package)
  ;; internal procedures
  (define (numer x) (car x))
  (define (denom x) (cdr x))
  (define (make-rat n d)
    (let ((g (gcd n d)))
      (cons (/ n g) (/ d g))))
  (define (add-rat x y)
    (make-rat (+ (* (numer x) (denom y))
                 (* (numer y) (denom x)))
              (* (denom x) (denom y))))
  (define (sub-rat x y)
    (make-rat (- (* (numer x) (denom y))
                 (* (numer y) (denom x)))
              (* (denom x) (denom y))))
  (define (mul-rat x y)
    (make-rat (* (numer x) (numer y))
              (* (denom x) (denom y))))
  (define (div-rat x y)
    (make-rat (* (numer x) (denom y))
              (* (denom x) (numer y))))
  (define (equ?-rat x y)
    (and (= (numer x) (numer y))
         (= (denom x) (denom y))))
  (define (=zero?-rat x) (zero? (numer x)))
  ;; interface to rest of the system
  (define (tag x) (attach-tag 'rational x))
  (put 'add '(rational rational)
       (lambda (x y) (tag (add-rat x y))))
  (put 'sub '(rational rational)
       (lambda (x y) (tag (sub-rat x y))))
  (put 'mul '(rational rational)
       (lambda (x y) (tag (mul-rat x y))))
  (put 'div '(rational rational)
       (lambda (x y) (tag (div-rat x y))))
  (put 'equ? '(rational rational) equ?-rat)
  (put '=zero? '(rational) =zero?-rat)
  (put 'raise '(rational) (lambda (n) (make-real (exact->inexact (/ (numer n) (denom n))))))
  (put 'make '(rational)
       (lambda (n d) (tag (make-rat n d))))
  'done)
(define (make-rational n d)
  ((get 'make '(rational)) n d))

(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))
(define (magnitude z) (apply-generic 'magnitude z))
(define (angle z) (apply-generic 'angle z))
(define (install-complex-package)
  ;; imported procedures from rectangular and polar packages
  (define (make-from-real-imag x y)
    ((get 'make-from-real-imag 'rectangular) x y))
  (define (make-from-mag-ang r a)
    ((get 'make-from-mag-ang 'polar) r a))
  ;; internal procedures
  (define (add-complex z1 z2)
    (make-from-real-imag (+ (real-part z1) (real-part z2))
                         (+ (imag-part z1) (imag-part z2))))
  (define (sub-complex z1 z2)
    (make-from-real-imag (- (real-part z1) (real-part z2))
                         (- (imag-part z1) (imag-part z2))))
  (define (mul-complex z1 z2)
    (make-from-mag-ang (* (magnitude z1) (magnitude z2))
                       (+ (angle z1) (angle z2))))
  (define (div-complex z1 z2)
    (make-from-mag-ang (/ (magnitude z1) (magnitude z2))
                       (- (angle z1) (angle z2))))
  (define (equ?-complex z1 z2)
    (and (= (real-part z1) (real-part z2))
         (= (imag-part z1) (imag-part z2))))
  (define (=zero?-complex z) (and (zero? (real-part z))
                                  (zero? (imag-part z))))
  ;; interface to rest of the system
  (define (tag z) (attach-tag 'complex z))
  (put 'add '(complex complex)
       (lambda (z1 z2) (tag (add-complex z1 z2))))
  (put 'sub '(complex complex)
       (lambda (z1 z2) (tag (sub-complex z1 z2))))
  (put 'mul '(complex complex)
       (lambda (z1 z2) (tag (mul-complex z1 z2))))
  (put 'div '(complex complex)
       (lambda (z1 z2) (tag (div-complex z1 z2))))
  (put 'make-from-real-imag 'complex
       (lambda (x y) (tag (make-from-real-imag x y))))
  (put 'make-from-mag-ang 'complex
       (lambda (r a) (tag (make-from-mag-ang r a))))
  (put 'equ? '(complex complex) equ?-complex)
  (put '=zero? '(complex) =zero?-complex)
  'done)

(define (install-polar-package)
  ;; internal procedures
  (define (magnitude z) (car z))
  (define (angle z) (cdr z))
  (define (make-from-mag-ang r a) (cons r a))
  (define (real-part z)
    (* (magnitude z) (cos (angle z))))
  (define (imag-part z)
    (* (magnitude z) (sin (angle z))))
  (define (make-from-real-imag x y) 
    (cons (sqrt (+ (square x) (square y)))
          (atan y x)))
  (define (equ? x y)
    (and (= (magnitude x) (magnitude y))
         (= (angle x) (angle y))))
  (define (=zero? x) (zero? (magnitude x)))
  ;; interface to the rest of the system
  (define (tag x) (attach-tag 'polar x))
  (put 'real-part '(polar) real-part)
  (put 'imag-part '(polar) imag-part)
  (put 'magnitude '(polar) magnitude)
  (put 'angle '(polar) angle)
  (put 'equ? '(polar polar) equ?)
  (put '=zero? '(polar) =zero?)
  (put 'make-from-real-imag 'polar
       (lambda (x y) (tag (make-from-real-imag x y))))
  (put 'make-from-mag-ang 'polar 
       (lambda (r a) (tag (make-from-mag-ang r a))))
  'done)

(define (install-rectangular-package)
  ;; internal procedures
  (define (real-part z) (car z))
  (define (imag-part z) (cdr z))
  (define (make-from-real-imag x y) (cons x y))
  (define (magnitude z)
    (sqrt (+ (square (real-part z))
             (square (imag-part z)))))
  (define (angle z)
    (atan (imag-part z) (real-part z)))
  (define (make-from-mag-ang r a) 
    (cons (* r (cos a)) (* r (sin a))))
  (define (equ? x y)
    (and (= (real-part x) (real-part y))
         (= (imag-part x) (imag-part y))))
  (define (=zero? x) (and (zero? (real-part x))
                          (zero? (imag-part x))))
  ;; interface to the rest of the system
  (define (tag x) (attach-tag 'rectangular x))
  (put 'real-part '(rectangular) real-part)
  (put 'imag-part '(rectangular) imag-part)
  (put 'magnitude '(rectangular) magnitude)
  (put 'angle '(rectangular) angle)
  (put 'equ? '(rectangular rectangular) equ?)
  (put '=zero? '(rectangular) =zero?)
  (put 'make-from-real-imag 'rectangular 
       (lambda (x y) (tag (make-from-real-imag x y))))
  (put 'make-from-mag-ang 'rectangular 
       (lambda (r a) (tag (make-from-mag-ang r a))))
  'done)

(define (make-complex-from-real-imag x y)
  ((get 'make-from-real-imag 'complex) x y))
(define (make-complex-from-mag-ang r a)
  ((get 'make-from-mag-ang 'complex) r a))

(install-rational-package)
(install-scheme-number-package)
(install-complex-package)
(install-polar-package)
(install-rectangular-package)
(install-real-number-package)

Я уверен, что есть лучший способ решить эту проблему. Как я могу улучшить мое решение?



234
1
задан 8 мая 2011 в 07:05 Источник Поделиться
Комментарии