I am using Intermediate Student with Lambda in DrRacket, I was wondering how one would remove the duplicates in a list, while keeping the order. For example (remove-dup (list 2 5 4 5 1 2))
would produce (list 2 5 4 1)
. So far, I have this:
(define (remove-duplicates lst)
(cond
[(empty? lst) empty]
[(member? (first lst) (rest lst))
(remove-duplicates (rest lst))]
[else (cons (first lst) (remove-duplicates (rest lst)))]))
, but there's a problem since it doesn't keep the order. Can someone point me in the right direction? Thanks for your time.
If your goal is to get the functionality working, and not some homework question, then you don't need to do anything, just use remove-duplicates
:
Welcome to Racket v5.2.
-> (remove-duplicates (list 2 5 4 5 1 2))
'(2 5 4 1)
This is the solution:
(define (remove-duplicates lon)
(foldr (lambda (x y) (cons x (filter (lambda (z) (not (= x z))) y))) empty lon))
Old question, but this is an implementation of J-Y's idea.
(define (dup-rem lst)
(cond
[(empty? lst) empty]
[else (cons (first lst) (dup-rem (filter (lambda (x) (not (equal? (first lst) x))) lst)))]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With