delete-doubles function (scheme)

88 Views Asked by At
(define (delete-doubles lst)
  (cond ((null? lst) '())
        ((null? (cdr lst)) (car lst))
        ((equal? (car lst) (cadr lst)) (delete-doubles (cdr lst)))
        (else (cons (car lst) (delete-doubles (cdr lst))))))

This is the code I made. It is meant for deleting an element in a list when this element shows up two or more times after each other. The code works totally fine, apart from this:

> (delete-doubles '(1 2 2 3 4 5))
(1 2 3 4 . 5)

I'd like to remove the . , and I know it has something to do with the cons, but I don't know how to solve it.

Thanks in advance.

3

There are 3 best solutions below

0
On

when the cdr is null you are just returning the car, and in the else line you are doing cons on car and recursion on cdr. So that is where your pair is coming from. Does that help?

0
On

'(1 2 3) really means (cons 1 (cons 2 (cons 3 null)))

'(1 2 . 3) really means (cons 1 (cons 2 3)

A couple of good test cases should reveal the problem quickly. In general, you should start with the absolute smallest test case you can think of. Then the next smallest. Then go up from there. Don't jump straight to a big example.

0
On

I ran your code unchanged and got this:

> (delete-doubles '(1))
1

The intended output is (1).

This implies that you are returning the wrong value in the list-is-one-element-long-clause.

If the list has one element, then it is already without doubles. That is, you must return lst and not (car lst) in this case.