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 @   再思即可  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示