在Common Lisp中使用字符串对象作为散列键 [英] Using string object as a hash key in Common Lisp

查看:113
本文介绍了在Common Lisp中使用字符串对象作为散列键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个字典类型 - 即以字符串为键的哈希表。在Lisp中这是可能的还是明智的?

I'm trying to create a "dictionary" type - ie hash table with a string as a key. Is this possible or wise in Lisp?

我注意到这样可以预期:

I noticed that this works as expected:

> (setq table (make-hash-table))
#<HASH-TABLE :TEST EQL size 0/60 #x91AFA46>
> (setf (gethash 1 table) "one")
"one"
> (gethash 1 table)
"one"

但是,以下内容不是: p>

However, the following does not:

> (setq table (make-hash-table))
#<HASH-TABLE :TEST EQL size 0/60 #x91AFA0E>
> table
#<HASH-TABLE :TEST EQL size 0/60 #x91AFA0E>
> (setf (gethash "one" table) 1)
1
> (gethash "one" table)
NIL
NIL


推荐答案

您需要制作使用equal而不是eql的哈希表。 'eql不会评估两个具有相同内容的字符串,而'等于'。

You need to make hash-table that uses 'equal instead if 'eql. 'eql doesn't evaluate two strings with same content to 't, while 'equal does.

这是你如何做的:

(make-hash-table :test 'equal)

正如skypher所指出的,如果你想要区分大小写的字符串散列,你也可以使用equalp。

As skypher noted you can also use 'equalp instead if you want case-insensitive string hashing.

这篇关于在Common Lisp中使用字符串对象作为散列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆