Emacs Lisp:如何避免插入重复的列表项?

λ J*_*kas 11 emacs elisp

如何检查字符串是否已经存在于Emacs Lisp的列表中?我需要检查某个路径字符串是否已经在exec-path中,然后将其添加到该列表中(如果不是).谢谢!

cob*_*bal 20

add-to-list函数将在添加之前自动检查

(setq a '(1 2 3))
(add-to-list 'a 4)
(add-to-list 'a 3)
Run Code Online (Sandbox Code Playgroud)

将导致a等于(4 1 2 3)

来自Ch f add-to-list:

add-to-list is a compiled Lisp function in `subr.el'.
(add-to-list list-var element &optional append compare-fn)

Add element to the value of list-var if it isn't there yet.
The test for presence of element is done with `equal',
or with compare-fn if that's non-nil.
If element is added, it is added at the beginning of the list,
unless the optional argument append is non-nil, in which case
element is added at the end.

The return value is the new value of list-var.

If you want to use `add-to-list' on a variable that is not defined
until a certain package is loaded, you should put the call to `add-to-list'
into a hook function that will be run only after loading the package.
`eval-after-load' provides one way to do this.  In some cases
other hooks, such as major mode hooks, can do the job.

  • 这很棒!谢谢! (3认同)