Kumar Anand
Kumar Anand

Reputation: 189

LISP - remove duplicates from the given list of atoms

I am trying to remove the duplicate occurrences of the atoms in the given list.
My code is as below -

(defun combine (item List)
 (if (member item List)
   List (cons item List)))

(defuneliminateDuplicates(L)
    (do
      ((M L) M)
      ((null L) M)
      (setq M (combine (car L) M))
      (setq L (cdr L))
))

This code works fine, it removes duplicates from the list -

[3]> (eliminateduplicates '(a b b c a c g a))
(G C B A)
[4]> (eliminateduplicates '(a a a a a a))
(A)
[5]> (eliminateduplicates '(a b c d))
(D C B A)

Here, I want the results to be in the same order as they are present in the given list.
i.e., the result of the (eliminateduplicates '(a b b c a c g a)) should be (B C G A), but not (G C B A)

How can I achieve this? Thanks.

Upvotes: 1

Views: 6181

Answers (1)

Óscar López
Óscar López

Reputation: 236004

I suggest using a different approach, it's simpler and the result is as expected:

(defun eliminateDuplicates (L)
  (cond ((null L) L)
        ((member (car L) (cdr L))
         (eliminateDuplicates (cdr L)))
        (t (cons (car L) (eliminateDuplicates (cdr L))))))

For example:

(eliminateDuplicates '(a b b c a c g a))
=> (B C G A)

Upvotes: 6

Related Questions