Paste here the answer of Ex3.16 and Ex3.17.
count-pairs function may return unexpected result
due to the introduction of set-car! etc.
Here we can show how it return 7 when there are just 3 pairs.
Also show the modified version of this function.
set-car!などにより、count-pairs関数が予想外の結果
を返してしまうことがある。ペアが三つなのに、7を返すケースを示します。
また、修正後の関数は以下の通りになります。
使用set-car!等可以任意改变pair的内容,导致count-pairs函数返回
我们并不期待的值。比如下面的例子显示此函数返回7。而实际上只有3个pair。
(define (count-pairs x)
(let ((ref '()))
(define (count-iter z)
(if (not (pair? z))
0
(if (counted? z ref) 0
(begin
(set! ref (append ref (list z)))
(+ (count-iter (car z))
(count-iter (cdr z))
1)))))
(count-iter x)))
(define (counted? y rf)
(if (null? rf) #f
(if (eq? y (car rf)) #t
(counted? y (cdr rf)))))
counted?
gosh> (count-pairs '(1 2 3))
3
gosh> (define k '( 1 2 3))
k
gosh> (set-car! k (cdr k))
gosh> (set-car! (cdr k) (cddr k))
gosh> (count-pairs k)
3
No comments:
Post a Comment