常见的 lisp 哈希表

Nex*_*Nex 2 hashtable common-lisp

任务是读取像“name phone”这样的N个字符串并存入。然后通过像“name”这样的请求找到存储的数据。我的代码将名称和数字存储在哈希表中,但之后找不到任何值。使用 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)))))
Run Code Online (Sandbox Code Playgroud)

样本输入:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Run Code Online (Sandbox Code Playgroud)

Vat*_*ine 5

除非您指定测试函数,否则哈希表将使用 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*)))
Run Code Online (Sandbox Code Playgroud)

这将生成输出:

Using EQ, the result is NIL
Using EQL, the result is NIL
Using EQUAL, the result is T
Using EQUALP, the result is T
Run Code Online (Sandbox Code Playgroud)

在这种情况下,equal和之间的主要区别在于equalp后者不区分大小写,而前者不区分大小写。要使用另一个测试函数,请使用:test关键字和找到的“标准”测试函数之一。如果你并不需要区分大小写的比赛,你会简单地创建哈希表是这样的:(make-hash-table :test #'equal)