Reputation: 3
When I typed my original solution to subproblem b. of exercise 2.29 in SICP:
(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)))))))
and tested it with the following data:
(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)
The interpreter (MIT/GNU Scheme) reported error: "the object 3, passed as the first argument to cdr, is not the correct type". But when I eliminated the expression
(let ((left (left-branch m))
(right (right-branch m)))
...)
with the following code:
(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)))))))
the program worked fine and printed the result
;Value: 27
I got confused. Can anybody take a trial on this problem and help me out?
Upvotes: 0
Views: 284
Reputation: 6315
The problem is that in the first version, (left-branch m)
and (right-branch m)
is called before you check whether or not m
represents a mobile. i.e. m
can be
a number, or nil
.
Upvotes: 4