问题
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))
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
.
all in all neither x or y has been changed. Only thing added memory wise is the dotted pair.
However when I call append with the two lists:
(append 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
.
Are my assumptions correct?
回答1:
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))
will result in:
(list 'hi ',hello)
(list 'randomvalue1 ',randomvalue2)
Do you mean to write:
(define x '(hi hello))
(define y '(randomvalue1 randomvalue2))
which results in:
(list 'hi 'hello)
(list 'randomvalue1 'randomvalue2)
?
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))]))
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.
来源:https://stackoverflow.com/questions/35115348/difference-between-append-and-cons-racket