删除所有但非重复的(球拍)

时间:2015-04-06 15:14:32

标签: duplicates racket abstraction fold

我知道如何使函数删除所有重复项,但这不是我的问题。我希望保留一切独特/没有重复的内容。

如果有人可以在他们的回复中使用抽象/高阶函数,那将是特别好的

所以这里有一些例子;

'(1 1 1 2 2 2 3 4 5) - > '(3 4 5)

'(1 1 1 2 2 2) - >空

'(2 3 4) - > '(2 3 4)

2 个答案:

答案 0 :(得分:1)

这是使用bagifyiterations and comprehensions在Racket中的惯用O(n)解决方案。诀窍在于计算每个元素的出现次数,并且只计算那些元素的出现次数:

(define (bagify lst)
  (foldl (lambda (key ht)
           (hash-update ht key add1 0))
         #hash() lst))

(define (non-dups lst)
  (for/list ([key+value (in-hash-pairs (bagify lst))]
             #:when (= (cdr key+value) 1))
    (car key+value)))

例如:

(non-dups '(1 1 1 2 2 2 3 4 5))
=> '(3 4 5)

(non-dups '(1 1 1 2 2 2))
=> '()

(non-dups '(2 3 4))
=> '(2 3 4)

答案 1 :(得分:0)

#lang racket

(define (elements xs)
  (set->list (list->set xs)))

(define (duplicates xs)
  (elements
   (for/fold ([xs xs]) ([u (elements xs)])
     (remove u xs))))

(define (uniques xs)
  (remove* (duplicates xs) xs))

(define (remove-duplicates xs)
  (remove* (duplicates xs) xs))

(define (remove-non-duplicates xs)
  (remove* (uniques xs) xs))

(define xs  '(1 1 1 2 3 4 4))
(uniques xs)
(duplicates xs)
(remove-duplicates xs)
(remove-non-duplicates xs)

输出:

'(2 3)
'(4 1)
'(2 3)
'(1 1 1 4 4)