(define (remove-dups lst)

(cond

((null? lst) '())

((null? (cdr lst)) (display(car lst)))

((equal? (car lst) (car(cdr lst))) ---> NOT SURE WHAT TO DO HERE <-----)

(else (display(car lst)) (remove-dups(cdr lst)))))

Solved

Posted on 2011-04-20

I need to write a function that leaves only the elements that are not repeated in string (a b a a a c c).

The result would be (a b).

I am new to Scheme and LISP so this is all very confusing to me, expecially recursion.

Any help is appreciated.

The result would be (a b).

I am new to Scheme and LISP so this is all very confusing to me, expecially recursion.

Any help is appreciated.

15 Comments

(define (remove-dups lst)

(cond

((null? lst) '())

((null? (cdr lst)) (display(car lst)))

((equal? (car lst) (car(cdr lst))) ---> NOT SURE WHAT TO DO HERE <-----)

(else (display(car lst)) (remove-dups(cdr lst)))))

In any case, with Scheme, it's better to think in terms of the first element and the rest of the elements rather that the 1st and 2nd elements. For example, to find unique elements, cons the first element with everything in the rest of the list except for the first element (but after first applying the function recursively on the rest of the list).

I basically need to remove all consecutive duplicates.

I need my final result to be (a b),

by leaving only the elements that are not consecutively repeated in the string (a b a a a c c).

You suggestion would result in (a b a c). I need (a b).

I can think of one way to do it.

You need to look at three at a time.

If the first two don't match, print the first one, remove it, and call the function again.

If the first two match but don't match the third, remove both and call.

If all three match, remove one and call this way you can still tell it was a duplicate on the next call.

(define (remove-dups lst)

(cond

((null? lst) '())

((null? (cdr lst)) (display(car lst)))

((null? (cdr(cdr lst))) (remove-dups-helper lst))

((not(equal? (car lst) (car(cdr lst)))) (display(car lst)) (remove-dups(cdr lst)))

((not(equal? (car lst) (car(cdr(cdr lst))))) (remove-dups(cdr(cdr lst))))

((equal? (car lst) (car(cdr(cdr lst)))) (remove-dups(cdr lst)))

))

(define (remove-dups-helper lst)

(cond

((equal? (car lst) (car(cdr lst))) '())

(else (display(car lst)) (display(car(cdr lst))))))

http://www.experts-exchang

I'll be closing this question shortly.

Title | # Comments | Views | Activity |
---|---|---|---|

sum13 challenge | 24 | 69 | |

no14 challenge | 14 | 46 | |

maxMirror challenge | 10 | 70 | |

wordcount challenge | 11 | 49 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**18** Experts available now in Live!