0

当我输入子问题 b 的原始解决方案时。SICP 中的练习 2.29:

(define (total-weight m)
  (let ((left (left-branch m))
        (right (right-branch m)))
    (cond ((null? m) 0)
          ((not (pair? m)) m)
          (else
           (+ (total-weight (branch-structure left))
              (total-weight (branch-structure right)))))))

并用以下数据对其进行了测试:

(define left1 (make-branch 5 8))
(define right1 (make-branch 7 10))
(define m1 (make-mobile left1 right1))
(define right2 (make-branch 1 3))
(define m2 (make-mobile left2 right2))
(define left0 (make-branch 12 m1))
(define right0 (make-branch 5 m2))
(define m0 (make-mobile left0 right0))
(total-weight m0)

解释器 (MIT/GNU Scheme) 报告错误:“作为第一个参数传递给 cdr 的对象 3 不是正确的类型”。但是当我消除了表达

(let ((left (left-branch m))
      (right (right-branch m)))
  ...)

使用以下代码:

(define (total-weight m)
  (cond ((null? m) 0)
        ((not (pair? m)) m)
        (else
         (+ (total-weight (branch-structure (left-branch m)))
            (total-weight (branch-structure (right-branch m)))))))

该程序运行良好并打印了结果

;Value: 27

我很困惑。任何人都可以对这个问题进行试验并帮助我吗?

4

1 回答 1

4

问题在于,在第一个版本中,(left-branch m)(right-branch m) 您检查是否m代表移动设备之前会调用它。iem可以是一个数字,或者nil.

于 2013-05-30T19:04:10.030 回答