Copy hash table in Lisp

I recently worked with hash tables in Common Lisp. I was 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 an example using maphash?

+4
source share
3 answers

Since clhs does not list the copy table function, I would suggest that maphash is the way to go.

(defun copy-table (table)
  (let ((new-table (make-hash-table
                    :test (hash-table-test table)
                    :size (hash-table-size table))))
    (maphash #'(lambda(key value)
                 (setf (gethash key new-table) value))
             table)
    new-table))

(let ((table (make-hash-table)))
  (mapcar #'(lambda(arg argg)
              (setf (gethash arg table) argg))
          '(1 2 3 4) '(a b c d))
  (format t "~a~%" table)
  (format t "~a~%" (copy-table table)))

#<HASH-TABLE :TEST EQL :COUNT 4 {10063C7F13}>
#<HASH-TABLE :TEST EQL :COUNT 4 {10063C86D3}>

However, this function does not take into account the special configurations of the hash table, but as an example, it should be sufficient.

+4
source

- -, -, . , , loop - ( 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))))
+5

Do not reinvent the wheel, use copy-hash-tablefrom Alexandria .

+2
source

All Articles