关联列表(简称alist)是Lisp中一种经典的键值对数据结构,由点对(cons cell)组成的列表形式存储,每个点对的car
部分为键(key),cdr
部分为值(value)。例如:
'((name . "Alice") (age . 30) (city . "New York"))
assoc
、rassoc
)直接操作alist。| 操作 | 函数示例 | 说明 |
|----------------|-----------------------------------|-----------------------------|
| 查找键 | (assoc 'name alist)
| 返回匹配的点对或nil
|
| 添加/更新 | (acons 'job "Engineer" alist)
| 新增键值对到列表头部 |
| 删除键 | (remove-if (lambda (x) (eq (car x) 'age)) alist)
| 过滤指定键的点对 |
| 获取所有键 | (mapcar #'car alist)
| 提取所有键的列表 |
remove-if-not
过滤所有匹配项,或改用哈希表。(defun alist-get (key alist &optional default)
(let ((pair (assoc key alist)))
(if pair (cdr pair) default)))
(defun alist-set (key value alist)
(cons (cons key value) (remove-if (lambda (x) (eq (car x) key)) alist)))
;; 使用示例
(setq my-alist '((x . 10) (y . 20)))
(alist-set 'z 30 my-alist) ; 新增键z
(alist-get 'x my-alist) ; 返回10
memq
优化的alist(如Emacs中的assq
)。mapcar
/reduce
实现复杂查询。没有搜到相关的文章