common-lisp - Common Lisp 哈希表

标签 common-lisp hashtable

任务是读取N个字符串(如“姓名电话”)并存储。然后通过“姓名”等请求查找存储的数据。 我的代码将名称和数字存储在哈希表中,但之后找不到任何值。存储的值使用maphash进行检查(它显示所有键值对)。

按空格分割的函数只是实用程序。

(defparameter data (make-hash-table))

(defun split-by-one-space (string) ; to split string: "aaa bbb" -> (aaa bbb)
    (loop for i = 0 then (1+ j)
          as j = (position #\Space string :start i)
          collect (subseq string i j)
          while j))

(dotimes (i (read)) ; input data
    (let* ((inp (read-line))
           (raw (split-by-one-space inp))
           (name (string (car raw)))
           (phone (cadr raw)))
         (format t "Adding: ~W ~W~%" name phone) ; debug
         (setf (gethash name data) phone)))
(maphash #'(lambda (k v) (format t "~a => ~a~%" k v)) data) ; this show all stored data
(loop for line = (read-line *standard-input* nil :eof)
      until (or (eq line :eof) (eq line nil))
      do
      (let ((key (gethash line data))) ; it cannot find anything. Why?
           (format t "Searching: ~W~%" line) ; debug
           (if (null key)
               (format t "Not found~%")
               (format t "~A=~A~%" (car key) (cdr key)))))

示例输入:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

最佳答案

除非您指定测试函数,否则哈希表将使用 eql 来确定“此键与该键是否相同”。

(defvar *s1* "a string")
(defvar *s2* "a string")
(loop for pred in '(eq eql equal equalp)
  do (format t "Using ~a, the result is ~a~%"
     pred (funcall pred *s1* *s2*)))

这会生成输出:

Using EQ, the result is NIL
Using EQL, the result is NIL
Using EQUAL, the result is T
Using EQUALP, the result is T

在这种情况下,equalequalp 之间的主要区别在于后者不区分大小写,而前者则不区分大小写。要使用其他测试函数,请使用 :test 关键字和找到的“标准”测试函数之一。如果您不需要不区分大小写的匹配,您只需创建哈希表,如下所示:(make-hash-table :test #'equal)

关于common-lisp - Common Lisp 哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762808/

相关文章:

multithreading - 设计一个hash_table,应该注意几个方面?

lisp - 如何在 Common Lisp 中删除符号的所有属性?

json - 防止使用 common-lisp YASON 库解析 JSON 节点

使用变量键的 Powershell Hashtable 值

c - 在 C 中通过 void 指针传递字符串时出现段错误

matlab - MATLAB 中的哈希表

variables - 在创建 lambda 时捕获变量的值

compilation - 使用 Clozure Common Lisp 编译二进制文件

lisp - 这个 Common Lisp 代码发生了什么?

hashtable - 哈希表后缀树解释