Hi all,
Trying to learn a bit about recursion in racket.
The question is to remove duplicates from a list while maintaining the order of the list.
one function to remove duplicates from the left,
i.e. 1 2 1 3 2 4 5 -> 1 2 3 4 5
and one from the right.
i.e. 1 2 1 3 2 4 5 -> 1 3 2 4 5
I've gotten the code to work by writing some helper functions, but my question is, is it possible to solve these problems WITHOUT:
- local definition (i.e. beginner student language in dr racket)
- loops
- built in 'remove', 'reverse', 'member?'
- writing your own 'remove', 'reverse', 'member?' functions
OR if 'member?' is allowed... I can figure out the right side case without additional functions, but not for the left case, is there a way to do this without the remove duplicates function that i wrote?
---
Code:
http://pastebin.com/h0dBdUaR
(define (RemoveElement element lst)
;if unique-left is applied to (list 1 4 2 1 5 4), the result would be (list 1 4 2 5)
(cond
[(empty? lst) empty]
[(= element (first lst)) (RemoveElement element (rest lst))]
[else (cons (first lst) (RemoveElement element (rest lst)))]))
(define (unique-left lst)
(cond
[(empty? lst) empty]
[(member? (first lst) (rest lst)) (cons (first lst) (unique-left (RemoveElement (first lst) (rest lst))))]
[else (cons (first lst) (unique-left (rest lst)))]
)
)
(define (unique-right lst)
;the result of applying it to (list 1 4 2 1 5 4) would be (list 2 1 5 4)
(cond
[(empty? lst) empty]
[(not (member? (first lst) (rest lst))) (cons (first lst) (unique-right (rest lst)))]
[else (unique-right (rest lst))]))