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

前端 未结 8 1279
情话喂你
情话喂你 2021-02-15 15:13

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

相关标签:
8条回答
  • 2021-02-15 15:56

    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

    0 讨论(0)
  • 2021-02-15 15:56

    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.

    0 讨论(0)
  • 2021-02-15 15:58

    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)
    
    0 讨论(0)
  • 2021-02-15 16:04

    This is the solution:

    (define (remove-duplicates lon)
      (foldr (lambda (x y) (cons x (filter (lambda (z) (not (= x z))) y))) empty lon))
    
    0 讨论(0)
  • 2021-02-15 16:07

    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!

    0 讨论(0)
  • 2021-02-15 16:13

    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 :)

    0 讨论(0)
提交回复
热议问题