计划列表中的组号?

时间:2017-11-17 12:09:39

标签: list split scheme racket

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

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

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这是一种方法:

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