追加和缺点球拍之间的区别

Difference between append and cons racket

我试图了解缺点与追加之间在列表存储方式方面的区别。考虑这种情况:

1
2
(define x '(hi, hello))
(define y '(randomvalue1, randomvalue2))

如果我假设那个电话
这两个列表上的(cons x y)将生成一个虚线对
其中第一个指针指向x,第二个指针指向y

总而言之,x或y均未更改。明智的添加记忆的只有点对。

但是,当我用两个列表调用append时:

1
(append x y)

我假设为了使球拍避免更改xy,它将必须创建一个新列表,其中包含按顺序复制xy值的条目。此列表没有任何指向xy的指针。

我的假设是否正确?


我更喜欢使用(list ...)编写列表,其中(list <c> <d>)(cons (cons (cons <c> (cons <d> empty))))

的简写

在提出您的问题之前,我想提一个问题:

1
2
(define x '(hi, hello))
(define y '(randomvalue1, randomvalue2))

将导致:

1
2
(list 'hi ',hello)
(list 'randomvalue1 ',randomvalue2)

你的意思是写:

1
2
(define x '(hi hello))
(define y '(randomvalue1 randomvalue2))

其结果是:

1
2
(list 'hi 'hello)
(list 'randomvalue1 'randomvalue2)

现在,对于您的问题,这是append的实现:

1
2
3
4
(define (append x y)
  (cond
    [(empty? x) y]
    [(cons? x) (cons (first x) (append (rest x) y))]))

直观上,它将x分解为元素,并重新排列元素以形成新列表。但是,y在整个函数中保持不变。因此,(append x y)结果中的y存储器地址仍指向与以前相同的y。对于x,不是。