2

I'm having trouble getting my hash table to reliably return values and I wonder whether someone might be able to advise?

Here's what I'm doing:

  1. Make table:

(setq table (make-hash-table))

  1. Define a variable for naming elements in the table, initial name is "bob" but in my program this will hold a user generated value, which will change from time to time:

(defvar name-of-element "bob")

  1. Add a row to the table, named after the contents of name-of-element:

(setf (gethash name-of-element table) "bob's element")

  1. When I retrieve the element from the table using the key name-of-element:

(gethash name-of-element table)

I get:

"bob's element"
T
  1. But when I try to retrieve using "bob":

(gethash "bob" table)

I get negative/no result:

N
N

Thoughts?

Oliver Cox
  • 105
  • 6
  • 1
    Please see [Equality predicates for hash tables](https://stackoverflow.com/q/24144210/850781) and [Why are there so many ways to compare for equality?](https://stackoverflow.com/q/24032028/850781) – sds Sep 28 '22 at 22:27
  • See also [Test if array is inside a list in lisp](https://stackoverflow.com/q/19287777/850781). – sds Sep 29 '22 at 02:48

1 Answers1

4

The default for the :test option to make-hash-table is eql. When you create a new string "bob", it's not eql to the value of name-of-element, e.g.

(eql "bob" name-of-element) => NIL

Use :test 'equal to get a hash table that considers similar strings to be equivalent.

(defvar *table* (make-hash-table :test 'equal))
Barmar
  • 741,623
  • 53
  • 500
  • 612