简体   繁体   English

缺陷指向相同的其他缺点

[英]Cons cells pointing to the same other cons

I want to create following list in Lisp. 我想在Lisp中创建以下列表。

两个cons单元的图片,第一个中的两个单元都指向第二个,其中包含A和B.

((lambda(x) (cons x x)) (cons'A 'B))

creates this list, but 创建此列表,但是

((lambda(x y) (cons x y)) (cons'A 'B) (cons 'A 'B))

and

(cons (cons 'A 'B) (cons 'A 'B))

do not create the list. 不要创建列表。

My challenge is why!? 我的挑战是为什么!? How does the first command create this list and the others do not? 第一个命令如何创建此列表而其他命令不创建? Any detail? 任何细节?

每次(cons 'A 'B)被调用时,都会创建一个新的 cons单元格,因此你的第二个表达式会创建两个 “相似”( equal但不是eql )的对象(A . B) eql (A . B)

You want to create a cons of A and B: 你想创建一个A和B的cons

(cons 'A 'B)

Then you want to refer to it twice from another cons. 然后你想从另一个缺点引用它两次。 So if x is a reference to this existing cons , you want 因此,如果x是对现有cons的引用,则需要

(cons x x)

Wrapping up, we get 结束,我们得到

(let ((x (cons 'A 'B)) (cons x x))

or equivalently 或者等价的

((lambda (x) (cons x x)) (cons 'A 'B))

If you do (cons 'A 'B) twice you create two cells: 如果你做两次(cons 'A 'B)你会创建两个单元格:

A B 一个 B.

A B 一个 B.

and the cons of those will contain one link to the first, and another to the second. 这些的cons将包含一个链接到第一个,另一个链接到第二个。

(Using a lambda to refer to them is a pointless obfuscation; the point of the example with the lambda form is that you use x twice. The form (使用lambda来引用它们是一种毫无意义的混淆;具有lambda形式的示例的要点是你使用x两次。

((lambda (x y) (cons x y)) (cons 'A 'B) (cons 'A 'B))

is just a very tedious way to write 写作只是一种非常乏味的方式

(cons (cons 'A 'B) (cons 'A 'B))

whereas in the original example there is -- pointedly -- only one instance of (cons 'A 'B) which you want to be able to refer to twice.) 而在最初的例子中,只有一个(cons 'A 'B)实例,你希望它能够引用两次。)

The purpose of this exercise is to illustrate the difference between "surface" equivalence and identity. 本练习的目的是说明“表面”对等与身份之间的区别。 Two lists which contain the same values are still two different lists, whereas two references to the same list are identical. 包含相同值的两个列表仍然是两个不同的列表,而对同一列表的两个引用是相同的。 As @sde hints, this makes a difference for understanding comparisons; 正如@sde提示的那样,这对理解比较有所帮助; the prototypical example is that equal is true for distinct lists containing the same values (as well as identical lists, of course), whereas eql is only true if its arguments are in fact identical (ie they refer to the same object). 原型的例子是, equal为含有相同的值不同的列表真(以及相同列表,当然),而eql是仅当它的参数实际上是相同的真(即,它们是指相同的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM