Subject: bug#78162: [PATCH] hash-table-contains-p: Avoid creating a symbol on every call

From: Helmut Eller <[email-masked]>
Date: Mon, 12 May 2025 10:17:32 +0200

On Sun, May 11 2025, Stefan Monnier via "Bug reports for GNU Emacs, the Swiss army knife of text editors" wrote:

> [ Ideally, this function would be replaced with one which doesn't return
>   just `t` but an actual "handle" on the hash-table slot, so that we can
>   then access that slot without redoing the key lookup.  It would allow
>   doing thing like `push` or `incf` on a hash-table entry without
>   looking up the key twice.
>   But doing so without allocating an object is hard with the current
>   hash-table design (and would come with its own downsides).  ]

Maybe something like the hashtable-update! function from R6RS would
work:

   (hashtable-update! hashtable key proc default)

   Proc should accept one argument, should return a single value, and
   should not mutate hashtable. The hashtable-update! procedure applies
   proc to the value in hashtable associated with key, or to default if
   hashtable does not contain an association for key. The hashtable is
   then changed to associate key with the value returned by proc.

   The behavior of hashtable-update! is equivalent to the following
   code, but may be implemented more efficiently in cases where the
   implementation can avoid multiple lookups of the same key:

   (hashtable-set! hashtable key
                   (proc (hashtable-ref hashtable key default)))

A problem with hashtable-update! seems to be that the proc argument is
often a lambda expression and would allocate.  Though, people who care
about that could perhaps use dynamic variables to avoid allocation a
closure.  On the positive side, this it doesn't need an explicit
"handle".

Helmut