summaryrefslogtreecommitdiff
path: root/src/hash-tables.lisp
blob: 9e41b266a2fd3813a5e0857d34179fdb307d8553 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
;; SPDX-License-Identifier: EUPL-1.2
;; SPDX-FileCopyrightText: 2025 Uko Kokņevičs <perkontevs@gmail.com>
(defpackage :ukkoclot/hash-tables
  (:use :c2cl)
  (:export :alist->hash-table :gethash-lazy :plist->hash-table))
(in-package :ukkoclot/hash-tables)

(defun alist->hash-table (alist &rest args &key &allow-other-keys)
  (let ((ht (apply #'make-hash-table args)))
    (loop for (key . value) in alist do
      (setf (gethash key ht) value))
    ht))

(defmacro gethash-lazy (key hash-table default-lazy)
  (let ((unique (gensym "UNIQUE-"))
        (res (gensym "RES-")))
    `(let* ((,unique ',unique)
            (,res (gethash ,key ,hash-table ,unique)))
       (if (eq ,res ,unique)
           ,default-lazy
           ,res))))

(defun plist->hash-table (plist &rest args &key &allow-other-keys)
  (let ((ht (apply #'make-hash-table args)))
    (loop for (key value) on plist by #'cddr do
      (setf (gethash key ht) value))
    ht))