Difference between append and cons racket

邮差的信 提交于 2020-01-04 04:31:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!