diff options
Diffstat (limited to 'src/hash-tables.lisp')
| -rw-r--r-- | src/hash-tables.lisp | 12 |
1 files changed, 10 insertions, 2 deletions
diff --git a/src/hash-tables.lisp b/src/hash-tables.lisp index 9e41b26..d3b66dd 100644 --- a/src/hash-tables.lisp +++ b/src/hash-tables.lisp | |||
| @@ -1,19 +1,24 @@ | |||
| 1 | ;; SPDX-License-Identifier: EUPL-1.2 | 1 | ;; SPDX-License-Identifier: EUPL-1.2 |
| 2 | ;; SPDX-FileCopyrightText: 2025 Uko Kokņevičs <perkontevs@gmail.com> | 2 | ;; SPDX-FileCopyrightText: 2025 Uko Kokņevičs <perkontevs@gmail.com> |
| 3 | (defpackage :ukkoclot/hash-tables | 3 | (defpackage :ukkoclot/hash-tables |
| 4 | (:documentation "Utilities for dealing with hash tables.") | ||
| 4 | (:use :c2cl) | 5 | (:use :c2cl) |
| 6 | (:import-from :alexandria :with-gensyms) | ||
| 5 | (:export :alist->hash-table :gethash-lazy :plist->hash-table)) | 7 | (:export :alist->hash-table :gethash-lazy :plist->hash-table)) |
| 6 | (in-package :ukkoclot/hash-tables) | 8 | (in-package :ukkoclot/hash-tables) |
| 7 | 9 | ||
| 8 | (defun alist->hash-table (alist &rest args &key &allow-other-keys) | 10 | (defun alist->hash-table (alist &rest args &key &allow-other-keys) |
| 11 | "Turn an association list into a hash table. | ||
| 12 | |||
| 13 | All key arguments are passed on to `make-hash-table'." | ||
| 9 | (let ((ht (apply #'make-hash-table args))) | 14 | (let ((ht (apply #'make-hash-table args))) |
| 10 | (loop for (key . value) in alist do | 15 | (loop for (key . value) in alist do |
| 11 | (setf (gethash key ht) value)) | 16 | (setf (gethash key ht) value)) |
| 12 | ht)) | 17 | ht)) |
| 13 | 18 | ||
| 14 | (defmacro gethash-lazy (key hash-table default-lazy) | 19 | (defmacro gethash-lazy (key hash-table default-lazy) |
| 15 | (let ((unique (gensym "UNIQUE-")) | 20 | "`gethash' alternative with lazily evaluated default value." |
| 16 | (res (gensym "RES-"))) | 21 | (with-gensyms (res unique) |
| 17 | `(let* ((,unique ',unique) | 22 | `(let* ((,unique ',unique) |
| 18 | (,res (gethash ,key ,hash-table ,unique))) | 23 | (,res (gethash ,key ,hash-table ,unique))) |
| 19 | (if (eq ,res ,unique) | 24 | (if (eq ,res ,unique) |
| @@ -21,6 +26,9 @@ | |||
| 21 | ,res)))) | 26 | ,res)))) |
| 22 | 27 | ||
| 23 | (defun plist->hash-table (plist &rest args &key &allow-other-keys) | 28 | (defun plist->hash-table (plist &rest args &key &allow-other-keys) |
| 29 | "Turn a property list into a hash table. | ||
| 30 | |||
| 31 | All key arguments are passed on to `make-hash-table'." | ||
| 24 | (let ((ht (apply #'make-hash-table args))) | 32 | (let ((ht (apply #'make-hash-table args))) |
| 25 | (loop for (key value) on plist by #'cddr do | 33 | (loop for (key value) on plist by #'cddr do |
| 26 | (setf (gethash key ht) value)) | 34 | (setf (gethash key ht) value)) |