List 方案中列表中的组号?

List 方案中列表中的组号?,list,split,scheme,racket,List,Split,Scheme,Racket,当给定一个列表时,我必须将列表拆分为多个列表,这些列表将相同的元素组合在一起 例如:‘(37 37 39 38 39 38 40 38)必须导致’((37 37)(39 39)(38 38 38)(40 40)) 有人能帮我吗?这里有一种方法: (define (group lst) (let iter ((lst lst) (found null) (res null)) (if (null? lst) ; all done ... (reverse res) ;

当给定一个列表时,我必须将列表拆分为多个列表,这些列表将相同的元素组合在一起

例如:‘(37 37 39 38 39 38 40 38)必须导致’((37 37)(39 39)(38 38 38)(40 40))


有人能帮我吗?

这里有一种方法:

(define (group lst)
  (let iter ((lst lst) (found null) (res null))
    (if (null? lst) ; all done ...
        (reverse res) ; ... return result (reversed)
        (let ((c (car lst))) ; isolate first element
          (if (member c found) ; already processed that
              (iter (cdr lst) found res) ; just go on with the next
              (iter (cdr lst) ; otherwise add this to found and create a list of as many elements ...
                    (cons c found) ; ... as found in the list to the current result ...
                    (cons (make-list (count (curry equal? c) lst) c) res))))))) ; ... and go on with the next
测试

> (group '(37 37 39 38 38 39 38 40 40 37))
'((37 37 37) (39 39) (38 38 38) (40 40))
> (group '(37 37 39 38 38 39 38 40 40 38))
'((37 37) (39 39) (38 38 38 38) (40 40))
结果应该是“((37 37)(39 39)(38 38)(40 40)),您可以使用:
(按身份分组)(37 37 39 38 39 38 40 38))