Search code examples
emacselisp

Stripping duplicate elements in a list of strings in elisp


Given a list such as

(list "foo" "bar" nil "moo" "bar" "moo" nil "affe")

how would I build a new list with the duplicate strings removed, as well as the nils stripped, i.e.

(list "foo" "bar" "moo" "affe")

The order of the elements needs to be preserved - the first occurence of a string may not be removed.

The lists I'm dealing with here are short, so there's no need to use anything like a hash table for the uniqueness check, although doing so certainly wouldn't hurt either. However, using cl functionality is not a viable option.


Solution

  • Try "Sets and Lists" in the "Lists" section of the Emacs Lisp Reference Manual:

    (delq nil (delete-dups (list "foo" "bar" nil "moo" "bar" "moo" nil "affe")))