Can CONS objects be used as a key to a hash table?

265 Views Asked by At

I've been playing with LISP lately, and I want to attempted to optimize a terribly inefficient recursive function by caching it's output so it only runs each combination of parameters once. I want to save the results into hash table, using either (LIST a b) or (CONS a b) as the key. My question is, is that even possible? Documentation I've read would lead me to believe it is, as the document I read defines the key as an 'object', and defines 'object' as something that was constructed with cons. So I gave this a try.

(defparameter *table* (make-hash-table))
(setf (gethash (list 1 2) *table*) 123)
(format t "~S~%" (gethash (list 1 2) *table*))

And it gives me NIL, when I would expect 123. If i replace the (list 1 2) with a cons it still doesn't work, but when I use an plain integer, it works fine.

I'm using GCL 2.6.12

2

There are 2 best solutions below

5
On BEST ANSWER
(make-hash-table :test #'equal)
0
On

Solutions for caching results of functions has been already implemented for Common Lisp. One is library fare-memoization, the second is function-cache and both are accessible with the Quicklisp. Using the former is as easy as defining normal function:

(define-memo-function your-time-consuming-function (arg)
    (code arg))

For reference please check https://github.com/fare/fare-memoization.