3

我似乎在这里遇到了猫在盒子里的问题下面的代码应该给定一个键和一个哈希表,返回与键对应的值,或者如果键不存在于地图中则返回错误:

(defun get-graph-node (key graph)
  (let ((result (gethash key graph)))
    (if (nth-value 1 result)
      (nth-value 0 result)
      (error "no node matches the key"))))

在大多数情况下,它确实如此,但我在运行时遇到了这种奇怪的情况:

(gethash 0 *g*)

返回

   #S(GRAPH-NODE$
      :DATA "("$
      :EDGES (#S(GRAPH-NODE :DATA "b" :EDGES NIL)$
              #S(GRAPH-NODE :DATA "a" :EDGES NIL)))
   T

(get-graph-node 0 *g*)

表示在 get-graph-node 中定义的错误

检查 *g* 给了我这个:

Count: 5
Size: 16
Test: EQL
Rehash size: 1.5
Rehash threshold: 1.0
[clear hashtable]
Contents: 
0 = #S(GRAPH-NODE :DATA "(" :EDGES (#S(GRAPH-NODE :DATA "b" :EDGES NIL) #S(GRAPH-NODE :DATA "a" :EDGES NIL))) 
[remove entry]
1 = #S(GRAPH-NODE :DATA "a" :EDGES NIL) [remove entry]
2 = #S(GRAPH-NODE :DATA "|" :EDGES (#S(GRAPH-NODE :DATA ")" :EDGES (NIL)))) [remove entry]
3 = #S(GRAPH-NODE :DATA "b" :EDGES NIL) [remove entry]
4 = #S(GRAPH-NODE :DATA ")" :EDGES (NIL)) [remove entry]

那么关键 0 应该在地图中吗?我向那位能告诉我我缺少什么的绅士致敬。

4

1 回答 1

6

将 gethash 的结果分配给变量 result 时,您只存储函数返回的多个值中的第一个。要同时存储它们,您应该执行以下操作:

(defun get-graph-node (key graph)
  (multiple-value-bind (result exists)
      (gethash key graph)
    (if exists
      result
      (error "no node matches the key"))))
于 2013-07-27T21:32:03.883 回答