0

I am trying to run this code that supposedly removes duplicates from a sorted list of numbers.

    (defun unique (x)
(cond( (null x) x )
( (null (cdr x)) x )( (equal (car x) (cdr x)) (unique (cdr x)) )( t (cons (car x) (unique (cdr x))) )))

I am trying to call this function by typing:

(print (unique '(2 2 3 4 4 5)))

My output is currently shown as follows:

(2 2 3 4 4 5)

Clearly, this doesn't seem to be removing the duplicates, if anything at all.

1 Answer 1

4

There is an error in the form: (equal (car x) (cdr x)). car returns the first element of a list, while cdr returns the rest of the list, so the comparison is not between the first and the second element of the list, but between the first element and the list without the first element (and this comparison will always produces false for regular lists).

To correct the error, the function should use cadr instead of cdr: (equal (car x) (cadr x)): the function cadr (or its synonym second) is equivalent to car (cdr and returns the second element of a list. So this is the correct version:

CL-USER> (defun unique (x)
           (cond ( (null x) x )
                 ( (null (cdr x)) x ) 
                 ( (equal (car x) (cadr x)) (unique (cdr x)) )
                 ( t (cons (car x) (unique (cdr x))) )))
UNIQUE
CL-USER> (unique '(1 1 2 2 3))
(1 2 3)
Sign up to request clarification or add additional context in comments.

4 Comments

"this comparison will always produce false" this calls for a counter-example :-) Consider (let* ((tail (list 0 1 2)) (list (cons tail tail))) (assert (equal (car list) (cdr list))))
Yes, and another counter-example is (1 . 1) :). I omitted “for regular lists”. Corrected, thanks @coredump.
It looks like this doesn't work for test case (print (unique '(2))) (print (unique '(2 2 3 4 4 5))), since it doesnt remove the extra 4
@Greg, it works for me: (unique '(2 2 3 4 4 5)) produces (2 3 4 5). On which system did you test it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.