Added a faster loop based remove-from-plist
[alexandria.git] / hash-tables.lisp
blob492ee1c58d8d3bf317a34c752d54f587a7857658
1 (in-package :alexandria)
3 (defun copy-hash-table (table &key
4 (test (hash-table-test table))
5 (size (hash-table-size table))
6 (rehash-size (hash-table-size table))
7 (rehash-threshold (hash-table-rehash-threshold table)))
8 "Returns a shallow copy of hash table TABLE, with the same keys and values
9 as the TABLE. The copy has the same properties as the original, unless
10 overridden by the keyword arguments."
11 (let ((copy (make-hash-table :test test :size size
12 :rehash-size rehash-size
13 :rehash-threshold rehash-threshold)))
14 (maphash (lambda (k v)
15 (setf (gethash k copy) v))
16 table)
17 copy))
19 (declaim (inline maphash-keys))
20 (defun maphash-keys (function table)
21 "Like MAPHASH, but calls FUNCTION with each key in the hash table TABLE."
22 (maphash (lambda (k v)
23 (declare (ignore v))
24 (funcall function k))
25 table))
27 (declaim (inline maphash-values))
28 (defun maphash-values (function table)
29 "Like MAPHASH, but calls FUNCTION with each value in the hash table TABLE."
30 (maphash (lambda (k v)
31 (declare (ignore k))
32 (funcall function v))
33 table))
35 (defun hash-table-keys (table)
36 "Returns a list containing the keys of hash table TABLE."
37 (let ((keys nil))
38 (maphash-keys (lambda (k)
39 (push k keys))
40 table)
41 keys))
43 (defun hash-table-values (table)
44 "Returns a list containing the values of hash table TABLE."
45 (let ((values nil))
46 (maphash-values (lambda (v)
47 (push v values))
48 table)
49 values))
51 (defun hash-table-alist (table)
52 "Returns an association list containing the keys and values of hash table
53 TABLE."
54 (let ((alist nil))
55 (maphash (lambda (k v)
56 (push (cons k v) alist))
57 table)
58 alist))
60 (defun hash-table-plist (table)
61 "Returns a property list containing the keys and values of hash table
62 TABLE."
63 (let ((plist nil))
64 (maphash (lambda (k v)
65 (setf plist (list* k v plist)))
66 table)
67 plist))
69 (defun alist-hash-table (alist &rest hash-table-initargs)
70 "Returns a hash table containing the keys and values of the association list
71 ALIST. Hash table is initialized using the HASH-TABLE-INITARGS."
72 (let ((table (apply #'make-hash-table hash-table-initargs)))
73 (dolist (cons alist)
74 (setf (gethash (car cons) table) (cdr cons)))
75 table))
77 (defun plist-hash-table (plist &rest hash-table-initargs)
78 "Returns a hash table containing the keys and values of the property list
79 PLIST. Hash table is initialized using the HASH-TABLE-INITARGS."
80 (let ((table (apply #'make-hash-table hash-table-initargs)))
81 (do ((tail plist (cddr tail)))
82 ((not tail))
83 (setf (gethash (car tail) table) (cadr tail)))
84 table))