Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme: Remove duplicated numbers from list

I wrote this code to create a list from en number of arguments given

(define (create-list . e)
   e)

But I need it to remove any duplicated numbers from the list within this block itself.

I have tried and searched for hours and can't find a solution without placing dozens of lines of code on other blocks.

For example let's say my input is

(create-list . 2 2 3 5 5 )

I need the list created to be '(2 3 5) and not '(2 2 3 5 5 )...

The order of the numbers doesn't matter.

like image 695
spacing Avatar asked Dec 05 '11 07:12

spacing


People also ask

How HashSet remove duplicates from a list?

Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements. HashSet<Integer>set = new HashSet<Integer>(list1); List<Integer>list2 = new ArrayList<Integer>(set); Above, the list2 will now have only unique elements.

How do you remove duplicates from a list in Python?

If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.


2 Answers

Basically, you need to do something like:

(define (create-list . e) (dedupe e))

I can think of a really simple but probably inefficient way to do this:

(define (dedupe e)
  (if (null? e) '()
      (cons (car e) (dedupe (filter (lambda (x) (not (equal? x (car e)))) 
                                    (cdr e))))))

If you can't use existing functions like filter, you can make one yourself:

(define (my-filter pred ls) 
  (cond ((null? ls) '())
        ((pred (car ls)) (cons (car ls) (my-filter pred (cdr ls))))
        (else (my-filter pred (cdr ls)))))
like image 92
Tikhon Jelvis Avatar answered Nov 05 '22 17:11

Tikhon Jelvis


This one is faster:

(define (remove-duplicates l)
  (cond ((null? l)
         '())
        ((member (car l) (cdr l))
         (remove-duplicates (cdr l)))
        (else
         (cons (car l) (remove-duplicates (cdr l))))))

But even better, mit-scheme provides delete-duplicates, which does exactly what you want.

like image 22
abo-abo Avatar answered Nov 05 '22 16:11

abo-abo