Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Hash Table in Lisp

I have recently been working with hash tables in Common Lisp. I have been wondering how to make a separate copy of a hash table containing all the same values as the first. Is there an official way to do this? If not, can you give me an example using maphash?

like image 665
Brooks Avatar asked Jun 10 '26 06:06

Brooks


1 Answers

Sim's answer copies a hash table, but there are two other features of hash tables thst might be good to copy for efficient population of the table. Here's a version that preserves that information, and also showcases loop's ability to work with hash tables (as an alternative to maphash):

(defun copy-hash-table (hash-table)
  (let ((ht (make-hash-table 
             :test (hash-table-test hash-table)
             :rehash-size (hash-table-rehash-size hash-table)
             :rehash-threshold (hash-table-rehash-threshold hash-table)
             :size (hash-table-size hash-table))))
    (loop for key being each hash-key of hash-table
       using (hash-value value)
       do (setf (gethash key ht) value)
       finally (return ht))))
                             
like image 193
Joshua Taylor Avatar answered Jun 15 '26 06:06

Joshua Taylor