Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to acquire unique object id in Emacs Lisp?

Tags:

emacs

elisp

Does emacs lisp have a function that provides a unique object identifier, such as e.g. a memory address? Python has id(), which returns an integer guaranteed to be unique among presently existing objects. What about elisp?

like image 604
nbtrap Avatar asked Aug 25 '12 14:08

nbtrap


2 Answers

The only reason I know for wanting a function like id() is to compare objects, and ensure that they only compare equal if they are the same (as in, in the same memory location). In Lisps, this is done a bit differently from in Python:

In most lisps, including elisp, there are several different notions of equality. The most expensive, and weakest equivalence is equal. This is not what you want, since two lists (say) are equal if they have the same elements (tested recursively with equal). As such

(equal (list 1 2) (list 1 2)) => T

is true. At the other end of the spectrum is eq, which tests "identity" rather than equality:

(eq (list 1 2) (list 1 2)) => NIL

This is what you want, I think.

So, it seems that Python works by providing one equality test, and then a function that gives you a memory location for each object, which then can be compared as integers. In Elisp (and at least Common Lisp too), on the other hand, there is more than one meaning of "equality".

Note, there is also "eql", which lies somewhere between the two.

(EDIT: My original answer probably wasn't clear enough about why the distinction between eq and equal probably solves the problem the original poster was having)

like image 162
Rupert Swarbrick Avatar answered Oct 14 '22 06:10

Rupert Swarbrick


There is no such feature in Emacs Lisp, as far as I know. If you only need equality, use eq, which performs a pointer comparison behind the scenes. If you need a printable unique identifier, use gensym from the cl package. If you need a unique identifier to serve as an index in a data structure, use gensym (or maintain your own unique id — gensym is simpler and less error-prone).

Some languages bake a unique id into every object, but this has a cost: either every object needs extra memory to store the id, or the id is derived from the address of the object, which precludes modifying the address. Python chooses to pay the cost, Emacs chooses not to.

like image 4
Gilles 'SO- stop being evil' Avatar answered Oct 14 '22 06:10

Gilles 'SO- stop being evil'