'(())和(cons null null)之间的区别 [英] Difference between '(()) and (cons null null)

查看:228
本文介绍了'(())和(cons null null)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对方案中'(())和(cons null null)之间的区别感到困惑.

I am confused about the difference between '(()) and (cons null null) in scheme.

下面的代码显示bc是完全相同的东西.

The code below show that b and c are completely the same thing.

(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时:

However, when I used dup instead of 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不同.我做了一些实验,但还不了解.

Variable b and c are different. I have done some experiments, but I haven't understand yet.

推荐答案

在第一个实现中,d的值是文字数据,并且修改后的结果不确定.为了突出显示正在发生的事情,请考虑以下代码:

The value of d in the first implementation is literal data, and is modified with undefined consequences. To highlight what's happening, consider the following code:

(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)的列表,并且第一次执行,但是连续的调用仍在访问相同数据:

The expected result is that (incorrect-list-null-and-x n) should return a list of the form (() n), and it does the first time, but successive calls are still accessing the same data:

(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返回的每个值实际上都是 same 对:

The same problem manifests itself a bit differently in your dup2. Every value returned from dup2 is actually the same pair:

(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))先前返回的相同结构.

because the call (dup2 (cons 3 4)) modifies the same structure that was previously returned by (dup2 (cons 1 2)).

这篇关于'(())和(cons null null)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆