开发者

how to allocate memory blocks, in clisp

开发者 https://www.devze.com 2023-02-27 00:56 出处:网络
in clisp (eq (cons \'a \'b) (cons \'a \'b)) is false(NIL) because first(AB) and second(AB) allocates in different memory.

in clisp

(eq (cons 'a 'b) (cons 'a 'b)) 

is false(NIL)

because first(AB) and second(AB) allocates in different memory.

and

(eq 'a(car '(开发者_如何学Goa b c)))

is true(T)

however, why?

like two (AB), does first A and second A which is result from (car '(a b c)) have to use different memory? how to allocate memory blocks, in clisp?


Each call to CONS creates a new cons cell. These are different objects.

(eq (cons 1 2) (cons 1 2)) -> NIL

Symbols with the same name are the same objects.

(eq 'foo 'foo) -> T

Complications:

Symbols with the same name, but in different packages are different objects.

(eq 'bar::foo 'baz::foo) -> NIL

Symbols with the same name without a package might be the same object or not.

(eq '#:foo '#:foo) -> NIL

(let ((sym '#:foo))
   (eq sym sym))
-> T


This is because 'a is interned. That is, whenever you type 'a in the code (in your second example, it occurs twice) they will resolve to the same symbol. This is because the reader will obtain a reference to the symbol using the INTERN function. (Hyperspec docs).

That is why (eq 'a 'a) returns T. There is one exception to this though. A symbol with the prefix #: will never be interned. This feature is used by GENSYM to guarantee that you get a unique symbol when writing macros.


CONS creates pairs. In your specific example, two pairs both containing the symbols A and B.

Typically, you don't worry about allocating memory blocks in Common Lisp, you create structures instead (arrays, lists, classes, hash tables). The only time you'd allocate memory bnlocks, as such, is for the purpose of calling functions linked in from another language.


Symbols are special objects. When Common Lisp first encounters a symbol, it is interned, i.e an object representing the symbol is created and the symbol is mapped to that object. For all further references to that symbol this object is retrieved using the symbol name as a key. For example, imagine that Common Lisp has created an object at memory location 0x05 for the symbol a. All further references to a will point to this same object. That means (eq 'a 'a) essentially becomes (eq 0x05 0x05) which evaluates to T.

Things are different for cons. Each call to cons creates a new object in memory. The first call to cons will create an object at, say, location 0x10 and the second call at 0x20. So your first comparison becomes (eq 0x10 0x20) which returns nil. The components of the pairs may point to the same objects, but the pairs themselves point to different locations.

0

精彩评论

暂无评论...
验证码 换一张
取 消