我对scheme中的“()”和(cons null null)之间的区别感到困惑。
下面的代码表明bc是完全相同的。

(define (dup2 x)
  (let ((d '(())))
    (set-car! d (car x))
    (set-cdr! d (cdr x))
    d))

(define a '(1 2))

(define b (dup2 a))
(define c (dup2 a))

(set-car! b 2)

> c  ;; --> (2 2)

但是,当我使用dup而不是dup2时:
(define (dup x)
  (let ((d (cons null null)))
    (set-car! d (car x))
    (set-cdr! d (cdr x))
    d))

(define a '(1 2))

(define b (dup a))
(define c (dup a))

(set-car! b 2)

> c  ;; --> (1 2)

变量bc是不同的我做了一些实验,但还不明白。

最佳答案

在第一个实现中,d的值是文本数据,并被修改为具有未定义的结果要突出显示正在发生的事情,请考虑以下代码:

(define (incorrect-list-null-and-x x)
  (let ((l '(())))                 ; a list of the form (() . ())
    (set-cdr! l (cons x (cdr l)))  ; (cdr l) is (), so (cons x (cdr l)) should be (x . ()) == (x), right?
                                   ; and now l should be (() . (x . ())) == (() x), right?
    l))

预期的结果是(incorrect-list-null-and-x n)应该返回一个(() n)表单的列表,并且它是第一次返回,但是连续的调用仍然访问相同的数据:
(incorrect-list-null-and-x 1) ;=> (() 1)
(incorrect-list-null-and-x 2) ;=> (() 2 1)
(incorrect-list-null-and-x 3) ;=> (() 3 2 1)
(incorrect-list-null-and-x 4) ;=> (() 4 3 2 1)

同样的问题在您的dup2中表现得有点不同从dup2返回的每个值实际上是同一对:
(let* ((x (dup2 (cons 1 2)))
       (y (dup2 (cons 3 4))))
  (display x)
  (display y))

输出:
(3 . 4)(3 . 4)

因为调用(dup2 (cons 3 4))修改了先前由(dup2 (cons 1 2))返回的相同结构。

09-26 21:57
查看更多