Common Lisp's copy-tree: Which objects will be

2019-02-26 23:53发布

I'm reading Practical Common Lisp, and have a question about Lisp's COPY-TREE function.

The book gives the example of calling

(copy-tree '( '(1 2) '(3 4) '(5 6)))

After explaining it, the book makes this statement:

Where a cons cell in the original referenced an atomic value, the corresponding cons cell in the copy will reference the same value. Thus, the only objects referenced in common by the original tree and the copy produced by COPY-TREE are the numbers 5, 6, and the symbol NIL.

But that doesn't make sense to me. I thought all atoms would be shared between the original and the new. Therefore, I expected that 1, 2, 3, 4, 5, 6 and NIL would all be shared between the original and the copy, and that the only "new objects" would be all the CONS cells.

Which one is correct, and why?

Thanks.

4条回答
唯我独甜
2楼-- · 2019-02-27 00:21

The description is correct, the example is not. copy-tree would return the 1, 2 and 3 as is, copying only the cons cells.

查看更多
迷人小祖宗
3楼-- · 2019-02-27 00:23

It is slightly more complicated.

The cons cells will be copied. Typically the objects the cons cells references will not be copied.

But there is one exception. Data like fixnums and characters can be stored inline in cons cells (and structure slots, class slots, arrays). Such data types are not necessarily EQ. That's why there is EQL.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-27 00:27

I check the web-version, a pdf version and the hard cover. The first two are wrong as you state. The hard cover states this (bold emphasis is mine):

Where a cons cell in the original referenced an atomic value, the corresponding cons cell in the copy will reference the same value. Thus, the only objects referenced in common by the original tree and the copy produced by COPY-TREE are the numbers 1-6, and the symbol NIL.

So the hard cover book is correct.

查看更多
Explosion°爆炸
5楼-- · 2019-02-27 00:32

Peter Seibel is reasonably assuming that numbers are stored directly in a cons cell rather than by reference:

Footnote 4, Chapter 12. They Called It LISP for a Reason: List Processing

Typically, simple objects such as numbers are drawn within the appropriate box, and more complex objects will be drawn outside the box with an arrow from the box indicating the reference. This actually corresponds well with how many Common Lisp implementations work--although all objects are conceptually stored by reference, certain simple immutable objects can be stored directly in a cons cell.

查看更多
登录 后发表回答