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 (remo
SRFI-1 has delete-duplicates
, although it's inefficient. (I am not too familiar with Racket, but surely it has SRFI-1, and the source...)
http://srfi.schemers.org/srfi-1/srfi-1.html#delete-duplicates
Run through the list sequentially, inserting each element in a hash table or other dictionary. If you try to insert an element that is already in the hash table, do not add it to the outgoing list.
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))
hmm i just had a racket exam recently, :/
the 'standard' remove-duplicates
works fine but i was using pretty-big in drRacket so it had to be loaded using (require racket/list)
here is an alternative way :)
using mutation (not really in the spirit of racket but.. it works.)
(define (set l)
(define the-set '())
(begin (for-each
(lambda (x)
(if (member x the-set)
#t
(set! the-set (cons x the-set))))
l)
(reverse the-set)))
hope this helps... cheers!
What you need to do is compare in reverse order the entire time. You can use the reverse
function which returns a list in reverse order. That way you are always removing the 2nd+ occurrence of an element and not the first. Here is an example, however it is using let
and if
and not a cond
expression.
http://www.cs.bgu.ac.il/~elhadad/scheme/duplicates.html
Good luck with your homework :)