append 和 cons 球拍的区别 [英] Difference between append and cons racket
问题描述
我试图了解 cons 和 append 在列表如何存储在下面方面的区别.考虑这种情况:
I'm trying to understand what the difference is between cons and append in terms of how the lists are being stored underneath. consider the case:
(define x '(hi, hello))
(define y '(randomvalue1, randomvalue2))
如果我假设调用(cons x y)
在这两个列表上会生成一个点对其中第一个指针指向 x
,第二个指针指向 y
.
if I'm assuming that calling
(cons x y)
on these two lists will generate a dotted pair
where the first pointer points to x
and the second points to y
.
总而言之,x 或 y 都没有改变.唯一增加记忆的是点对.
all in all neither x or y has been changed. Only thing added memory wise is the dotted pair.
但是,当我使用两个列表调用 append 时:
However when I call append with the two lists:
(append x y)
我认为,为了让球拍避免更改 x
和 y
,它必须为条目创建一个新列表,其中包含 x
和 y
的顺序.这个列表没有任何指向 x
或 y
的指针.
I would assume that in order for racket to avoid changing x
and y
it will have to create a new list with for entries with copies of the values of x
and y
in order. This list does not have any pointers pointing to neither x
or y
.
我的假设是否正确?
推荐答案
我更喜欢写列表,使用 (list ...)
where (list ; <c> <d>)
是 (cons <a> (cons <b> (cons <c> (cons <d> empty)))) 的简写
I prefer to write lists, using (list ...)
where (list <a> <b> <c> <d>)
is a shorthand for (cons <a> (cons <b> (cons <c> (cons <d> empty))))
在回答你的问题之前,我想提一个问题:
Before getting to your question, there is an issue I would like to mention:
(define x '(hi, hello))
(define y '(randomvalue1, randomvalue2))
将导致:
(list 'hi ',hello)
(list 'randomvalue1 ',randomvalue2)
你的意思是写:
(define x '(hi hello))
(define y '(randomvalue1 randomvalue2))
导致:
(list 'hi 'hello)
(list 'randomvalue1 'randomvalue2)
?
现在,对于您的问题,这里是 append
的实现:
Now, for your question, here's an implementation of append
:
(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
,它不会.
Intuitively, it destructs x
to elements and rearrange elements to form a new list. However, y
stays the same throughout the function. Thus, the memory address of y
in the result of (append x y)
still points to the same y
as before. For x
, it does not.
这篇关于append 和 cons 球拍的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!