Andre Viau
Andre Viau

Reputation: 275

Removing all duplicate members from a list in scheme

I am trying to remove duplicates in a list, using recursion. This is what I have. It only removes the first duplicate, not all of them.

My idea is to look at the first member, check if its a member of the rest of the list, if so, call the function again. If not, create a list with the first member and the result from calling the function again. I don't understand why it doesn't remove all the duplicates.

(define (removeDupes L)
  (cond ((null? L) ())
        ((list? (member (car L) (cdr L))) removeDupes (cdr L))
        (#T (cons ((car L) (removeDupes (cdr L)))))))

This is what I modified it to, and it works!! And I understand what was wrong with the cons. It needs two parameters and I only gave it one. I still have no Idea why the third line did not work....

(define (removeDupes L)
  (cond ((null? L) ())
        ((list? (member (car L) (cdr L)))(removeDupes(cdr L)))
        (#T (cons (car L) (removeDupes (cdr L))))))

Upvotes: 0

Views: 2378

Answers (1)

Gareth McCaughan
Gareth McCaughan

Reputation: 19971

There are multiple errors in your code, but the one that's probably causing the problem you've reported here is that your parentheses are wrong in the third line. You're trying to call removeDupes but your code doesn't actually do so; instead the value in that case ends up being (cdr L). Can you see why?

When you fix this, you'll find that your code starts producing errors. For the one you're likely to encounter first: take a careful look at how you're invoking cons on the last line. For the one you're likely to encounter next: remember that () is not self-evaluating in Scheme.

(I think this sort of thing is much harder to miss if you take care with the spacing and layout of your code. Put spaces between the elements of every list, for instance. Until you get so familiar with this stuff that these mistakes stop happening, you might want to make a habit of checking the parentheses any time you run across a mysterious error: have you missed a ( at the start of an expression, or put an extra ( before the arguments of a function, or forgotten the extra level of parens round a cond clause, or etc. etc. etc. Don't worry: after a while it'll stop happening...)

Upvotes: 3

Related Questions