【发布时间】:2021-10-06 19:58:37
【问题描述】:
简而言之:(gethash 'PARIS pandemic-hash-table) 返回 nil,尽管 'PARIS 是表中的键;这似乎与以某种方式在哈希表创建期间引用/评估符号有关,但我无法弄清楚。
我正在玩图形搜索(在棋盘游戏 Pandemic 中测试城市之间的最短路线;只是为了好玩 - 尝试以比“拥有最多边缘”更复杂的方式找到最佳研究实验室位置)。我正在使用哈希表来保存路由数据(节点和边),并且需要输入数据作为初步数据:
(defvar *nodes* '('San-Francisco 'Chicago 'Atlanta 'Washington 'Montreal 'New-York 'Madrid 'Paris 'London 'Essen 'Milan 'St-Petersburg))
(defvar *edges* '(('Chicago 'St-Petersburg)
('San-Francisco 'Atlanta 'Montreal)
('Chicago 'Washington)
('Atlanta 'Montreal 'New-York)
('Chicago 'Washington 'New-York)
('Montreal 'Washington 'Madrid 'London)
('New-York 'London 'Paris)
('Madrid 'Essen 'London 'Milan)
('Madrid 'Essen 'London 'New-York)
('London 'Paris 'Milan 'St-Petersburg)
('Paris 'Essen)
('Essen 'Chicago)))
(defvar *pandemic-node-hash* (make-hash-table))
(loop for node in *nodes*
for edges in *edges*
do (setf (gethash node *pandemic-node-hash*) edges))
如果我查看生成的哈希表:
CL-USER> (loop for key being the hash-keys of *pandemic-node-hash*
do (print key))
'SAN-FRANCISCO
... ;other keys removed for brevity
'PARIS
NIL
所以它正在制作表格(并且边缘显示类似),但是,(gethash 'PARIS *pandemic-node-hash*) 返回nil。如果我然后直接添加另一个'PARIS节点(setf (gethash 'paris *pandemic-node-hash*) 'somevalue),并检查密钥,我得到:
(loop for key being the hash-keys of *pandemic-node-hash*
do (print key))
'other keys
'PARIS
PARIS
NIL
所以,问题与在初始哈希表创建循环中对符号('PARIS 和朋友)的评估有关,但我不太清楚发生了什么或如何正确地做到这一点。我猜node 评估为 un 评估符号,将其传递给 gethash ...但是正确的方法是什么?肯定不是(评估节点)?反引号列表,符号前有逗号? (呃)。
【问题讨论】:
-
(defvar *nodes* '('San-Francisco 'Chicago ;;...))-- 为什么要同时引用列表和符号?只需(defvar *nodes* '(San-Francisco Chicago ;;...))。 -
当然,说出来就很简单!我不知何故认为你需要引用符号来传递它们,即使我不会写 ('3 '4 '5) 等。谢谢。
-
你需要引用符号来传递文字符号 -> 这样一个符号就不会被评估。但是您已经在列表中有符号。如果你调用
(foo (first *nodes*)),Lisp 将评估(first *nodes*),但不会再次评估结果。 -
在
'( ... )内,不会评估任何包含的数据,因此不需要引用任何数据以防止评估。
标签: lisp common-lisp