破坏性地将元素添加到列表中的惯用方法?

时间:2014-02-15 21:07:46

标签: emacs elisp

有没有一种很好的方法可以将元素添加到存储在变量中的列表中?我使用的方式不是很漂亮。

开始列表:

(setq sml/hidden-modes (list " hl-p"))

将项目添加到sml/hidden-modes

;; First way I append the items to hidden-modes and set it again
(setq sml/hidden-modes (append sml/hidden-modes
                               (list " AC" " Undo-Tree" " Smrt")))

;; Second way I use add-to-list to add items one at a time instead of all at once
(mapcar (lambda (mode) (add-to-list 'sml/hidden-modes mode))
        (list " AC" " Undo-Tree" " Smrt"))

;; Way I see people doing it in random .emacs snippets I find
(add-to-list 'sml/hidden-modes " AC")
(add-to-list 'sml/hidden-modes " Undo-Tree")
(add-to-list 'sml/hidden-modes " Smrt")

2 个答案:

答案 0 :(得分:3)

如果您事先知道原始列表是非零的,您可以尝试nconc

ELISP> (setq a '(1 2 3))
(1 2 3)

ELISP> (nconc a '(4 5 6))
(1 2 3 4 5 6)

ELISP> a
(1 2 3 4 5 6)

答案 1 :(得分:0)

dash列表库有!cons来预先添加元素:

(let ((xs '(2 3))) (!cons 1 xs) xs) ; (1 2 3)

除了GNU Emacs Lisp Reference ManualModifying Existing List Structure部分之外。