Search code examples
listduplicateslispelisp

Elisp: how to find list duplicates


I am using this to find list duplicates:

(defun have-dups (x)
  (let ((dups (copy-tree x)))
    (if (eq (length (delete-dups dups)) (length x))
    nil
      t)))

(have-dups (list 1 2 3 3)) ;=> t
(have-dups (list 1 2 3))   ;=> nil 

Considering the overhead of copy-tree and delete-dups, probably there is a better way.


Solution

  • Use a hash table, as soon as you find an element which already exists in the hash table, you know you have duplicates:

    (defun has-dup (list)
      (block nil
        (let ((hash (make-hash-table :test 'eql)))
          (map ()
               (lambda (item)
                 (if (gethash item hash)
                     (return t)
                   (setf (gethash item hash) t)))
               list))))