如何确保关联列表在Emacs中维护唯一的密钥 [英] How do you ensure an association list maintains unique keys in Emacs

查看:125
本文介绍了如何确保关联列表在Emacs中维护唯一的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定关键字被添加到诸如 auto-mode-alist 之类的关联列表的频率,我认为有一些惯用的方法来维护具有唯一键的关联列表,但是没有遇到它。

Given the frequency that keys are added to association lists like auto-mode-alist, I presume there is some idiomatic method for maintaining association lists with unique keys, but have yet to encounter it.

假设我执行以下操作:

(setq alist '())
(add-to-list 'alist '(a . 1))
(add-to-list 'alist '(a . 2))
(add-to-list 'alist '(b . 3))

运行后,alist包含((b。3)(a。2)(a。1))。我看到 add-to-list 可以采用可选的 compare-fn ,所以我假设有一些方法可以通过获得((b。3)(a。1))作为结果。我也知道我可以使用哈希表,但是很好奇如何用一个关联列表成语。

After running that, alist contains ((b . 3) (a . 2) (a . 1)). I see that add-to-list can take an optional compare-fn, so I presume there is some method I could pass to get ((b . 3) (a . 1)) as the result. I'm also aware I could use hash tables for this, but was curious how to do it idiomatically with an association list.

推荐答案

没有要求关联列表具有唯一的密钥,如您的示例所示,也没有什么特别的理由期望他们拥有唯一的密钥 - 在基础上,它只是一个列表,列表中没有限制

There's no requirement that association lists have unique keys, as your example shows, nor is there any particular reason to expect them to have unique keys -- at base, it's just a list of lists with no restrictions on the cars of the nested lists.

我相信利用这一事实来说,密钥没有限制来覆盖初始密钥/值对通过将新的对推到列表的前面。这些线条的一些核心功能是隐含的。在这里,例如,是 assoc 的文本序列:

I believe it's idiomatic to exploit the fact that there are no restrictions on the keys to override initial key/value pairs by pushing a new pair onto the front of the list. Some of the core functionality for alists works implicitly along these lines. Here, for example, is the docstring for assoc:

Return non-nil if KEY is `equal' to the car of an element of LIST.
The value is actually the first element of LIST whose car equals KEY.

因此,它只返回第一个元素,无论列表中稍后有多少其他元素,同样的关键这可能是一个非常有用的功能。

Hence, it returns only the first element, regardless of how many other elements come later in the list with the same key. That can be a pretty useful feature.

更新。如果你真的想阻止 add-to-list 从阴影之前的键/值对(虽然你是这样做的语言),你可以定义以下功能,并将其传递给 compare-fn 参数在 add-to-list (注意它没有错误检查):

Update. If you really want to prevent add-to-list from shadowing a prior key/value pair (although you're kind of fighting the language in doing so), you can define the following function and pass it to the compare-fn parameter in add-to-list (note that it does zero error-checking):

(defun key-used-p (elt1 elt2)
  "Helper function for add-to-list: returns non-nil if key is
already in use in an association list."
  (eq (car elt1) (car elt2)))

(setq alist '((a . 1) (b . 1) (c . 1)))        ; original list
(add-to-list 'alist '(a . 2) nil #'key-used-p) ; adds nothing because a in use
(add-to-list 'alist '(d . 2) nil #'key-used-p) ; adds (d . 2)

这篇关于如何确保关联列表在Emacs中维护唯一的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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