首页 > 解决方案 > 更新深层数据结构(Common Lisp)

问题描述

我想要一些关于访问和更新多层深的数据结构的建议。我最初想使用一个广义引用 setf 函数,但无法让它工作。作为替代方案,下面列出的函数可以正常工作以查询和更新数据结构(称为*kb*)。但它似乎比它需要的更复杂。有没有更简单的解决方案?

(defun fetch (node edge)
  "Retrieves all the nodes in the kb associated with a node and edge."
  (alexandria:hash-table-keys (cdr (assoc edge (gethash node *kb*)))))


(defun associate (node1 edge node2)
  "Adds an association to the kb."
  (declare (symbol node1 edge node2))
  (when (not (gethash edge *edges*))
    (error "Mentioned edge ~A was not predefined" edge))
  (let ((alist (gethash node1 *kb*)))
    (if alist
      (let ((pair (assoc edge alist)))
        (if pair
          (setf (gethash node2 (cdr pair)) t)
          (let ((ht (make-hash-table :test #'eq)))
            (setf (gethash node2 ht) t)
            (setf (gethash node1 *kb*) (acons edge ht alist)))))
      (let ((ht (make-hash-table :test #'eq)))
        (setf (gethash node2 ht) t)
        (setf (gethash node1 *kb*) (acons edge ht nil))))))

作为背景,*kb*数据结构是一个哈希表。哈希表键是符号,值是列表。每个 alist 由 key.value 对组成,其中键是符号,值是哈希表。后面的每个哈希表都简单地将一组符号表示为具有 t 个值的键。(ps:我为中间结构选择了alists,因为只有20个左右可能的边缘符号。)感谢您的任何见解......</p>

标签: data-structurescommon-lisp

解决方案


推荐阅读