sicp每日一题[2.82]

Exercise 2.82

Show how to generalize apply-generic to handle coercion in the general case of multiple arguments. One strategy is to attempt to coerce all the arguments to the type of the first argument,
then to the type of the second argument, and so on. Give an example of a situation where this strategy (and likewise the two-argument version given above) is not sufficiently general.
(Hint: Consider the case where there are some suitable mixed-type operations present in the table that will not be tried.)


这道题还是挺难的,题目的提示是通过一个双循环来依次进行类型转换,我参考别人的代码修改了很久最后才能跑通,用下面的代码替换上一题的 apply-generic 过程,可以验证是否能用。

(define (apply-generic op . args) 
  (define (no-method type-tags) 
    (error "No method for these types" 
           (list op type-tags)))
  
  (define (type-tags args) 
         (map type-tag args))

  ; 对每一个参数尝试进行强制类型转换
  (define (try-coerce-to target)
    (map (lambda (origin)
           (if (eq? (type-tag origin) (type-tag target))
               (lambda (x) x)   ; 如果类型一致,不进行转换
               (let ((coercor (get-coercion (type-tag origin) (type-tag target)))) 
                 (if coercor 
                     (coercor origin) 
                     origin)))) 
           args))
  
  (define (iterate next) 
    (if (null? next)
        (no-method (type-tags args)) 
        (let ((coerced (try-coerce-to (car next)))) 
          (let ((proc (get op (type-tags coerced)))) 
            (if proc 
                (apply proc (map contents coerced)) 
                (iterate (cdr next))))))) 
  
  (let ((proc (get op (type-tags args)))) 
    (if proc 
        (apply proc (map contents args)) 
        (iterate args))))
posted @ 2024-11-19 08:59  再思即可  阅读(1)  评论(0编辑  收藏  举报