sicp-2-5-2

Posted on 2015-02-25 07:03:37 +0900 in SICP Lisp

2.81

If try to coerce two numbers, it would fall into a infinite loop.

It would show an error message if trying to convert an augument to its own type, which is correct.

2.82

(define (apply-generic op . args)
  (define (apply-generic op args type-list)
    (if (null? type-list)
      (error "No method for types"
             (list op (map type-tag args))))
    (let ((new-args (map (lambda (x)
                           (convert x (car type-list)))
                         args)))
      (let ((new-tags (map type-tag new-args)))
        (let ((proc (get op new-tags)))
          (if proc
            (apply proc (map contents new-args))
            (apply-generic op args (cdr type-list)))))))
  (let ((type-tags (map type-tag args)))
    (let ((proc (get op type-tags)))
      (if proc
        (apply proc (map contents args))
        (apply-generic op args type-tags)))))

2.83

(define (raise x) (apply-generic 'raise x))
 (put 'raise 'integer
      (lambda (x) (make-rational x 1)))

 (put 'raise 'rational
      (lambda (x) (make-real (/ (numer x) (denom x)))))

 (put 'raise 'real
          (lambda (x) (make-from-real-imag x 0)))

2.84 ~ 2.97

I decided to skip the above ones just because they are so code intense, maybe I will come back to them in the future.

----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | sicp-2-5-1 »

Hide Comments

comments powered by Disqus