Lisp 中的内存分配
> (cons 2 3)
(2 . 3)
Lisp 环境只需要分配一个 cons cell 来连接这两个项目。
以上摘自Lisp书籍《Land of Lisp》。我不明白为什么这一对只位于一个缺点单元格中。这些数据的内存是什么样的?
> (cons 2 3)
(2 . 3)
The Lisp environment needs to allocate only a single cons cell to connect the two items.
Above is from the Lisp book "Land of Lisp". I don't understand why this pair is only located in a single cons cell. What does the memory look like for this data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
cons 单元始终保存两个值,称为
car
和cdr
:为了表示 cons 单元,Lisp 使用“点表示法”:
函数
cons
> 从它的两个参数创建这样一个 cons 单元:可以这样想:
cons 单元的值也可以是其他事物的“引用”或“指针”。例如,这些其他东西可以是其他 cons 单元:
这将是点表示法中的
(1 . (2 . nil))
。 Lisp 中使用这种链接来表示列表。由于列表用于表示代码,因此它们对于 Lisp 很重要。因此,它们有一个更短的表示法:(1 2)
。A cons cell always holds two values, called
car
andcdr
:To represent a cons cell, Lisp has the "dot notation":
The function
cons
creates such a cons cell from its two arguments:which can be thought of like this:
The values of a cons cell can also be "references" or "pointers" to other things. Those other things can, for example, be other cons cells:
This would be
(1 . (2 . nil))
in dot notation. This chaining is used in Lisp to represent lists. Since lists are used for the representation of code, they are important for Lisp. Therefore, there is a shorter notation for them:(1 2)
.CONS 单元格是具有两个字段的记录。
在许多 Lisp 实现中,有针对 cons 单元的特殊优化。一种典型的情况是,fixnum 数字直接存储在字段中 - 没有指针。只要数据适合内存,就可以直接存储。例如,对于字符来说也可能是这种情况。还可以存储具有两个字符的cons单元,使得字符被编码到字段中。
对于其他更大的数据,有指向存储在 cons 单元中的数据的指针。
然后还要注意以下之间的区别:
和
(cons 1 2)
创建单个 cons 单元。(list 1 2)
创建两个 con 单元格。第一个 cons 单元格包含 1 和指向第二个 cons 单元格的指针。第二个 cons 单元格包含 2 和 NIL(列表标记末尾)。因此,作为一种优化,通常在键/值对中仅使用 cons 单元而不使用列表。
与
后者使用两个以上的缺点电池。
A CONS cell is a record with two fields.
In many Lisp implementations there are special optimizations for cons cells. A typical one is that fixnum numbers are stored directly in the fields - without pointers. As long as the data fits into the memory, they can be stored directly. This may be for example also the case with characters. A cons cell with two characters may also be stored such that the characters are encoded into the fields.
With other, larger, data there are pointers to that data stored into the cons cell.
Then also note the difference between:
and
(cons 1 2)
creates a single cons cell.(list 1 2)
creates two cons cells. The first cons cell contains 1 and a pointer to the second one. The second cons cell contains 2 and NIL (the end of list marker).Thus as an optimization, often in key/value pairs one uses only the cons cell and not a list.
vs.
The latter uses two more cons cells.
我认为 lisp 中的缺点是这样的(只是为了解释,不是真正的代码)
这就是“单一缺点”的意思。
I think what's the cons in lisp is something like ( just for explanation, not the real code)
That's what the "single cons" means.
记忆是一种幻觉:
看,马,不需要记忆!
(只是在开玩笑)
Memory is an illusion:
Look Ma, no memory required !
(just kidding)