Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of duplicates in a list, but keep the order

Tags:

scheme

racket

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.

like image 388
J-Y Avatar asked Nov 16 '11 03:11

J-Y


3 Answers

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)
like image 54
Eli Barzilay Avatar answered Sep 21 '22 23:09

Eli Barzilay


This is the solution:

(define (remove-duplicates lon)
  (foldr (lambda (x y) (cons x (filter (lambda (z) (not (= x z))) y))) empty lon))
like image 32
Salem Talha Avatar answered Sep 21 '22 23:09

Salem Talha


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)))]))
like image 26
No_name Avatar answered Sep 21 '22 23:09

No_name