Search code examples
elisphashtable

compare hash table in emacs lisp?


It seems that equal can not compare hash table properly. Here is an exmaple

(defun hash-alist (alist)
  "Convert association list to a hash table and return it."
  (let ((my-hash (make-hash-table :test 'equal)))
    (dolist (entry alist)
      (puthash (car entry) (cdr entry) my-hash))
    my-hash))
(setq a '((?a . 1) (?b . 2)))
(setq b (hash-alist a))
(setq c (hash-alist a))
(equal b c)

The last line of code returns nil. Is there any other function to compare two hash tables?


Solution

  • since there is no function builtin Emacs to do this. I wrote it just in case people be interested:

    (defun hash-equal (hash1 hash2)
      "Compare two hash tables to see whether they are equal."
      (and (= (hash-table-count hash1)
              (hash-table-count hash2))
           (catch 'flag (maphash (lambda (x y)
                                   (or (equal (gethash x hash2) y)
                                       (throw 'flag nil)))
                                 hash1)
                  (throw 'flag t))))