2017-11-17 8 views
-1

リストが与えられたら、リストを同じ要素をグループ化するリストに分割する必要があります。例えばスキーム内のリストのグループ番号?

: '(37 37 39 38 38 39 38 40 40 38)を生じなければならない'((37 37)(39 39)(38 38 38 38)(40 40))

でき誰もがこれで私を助ける?

+0

結果がでなければなりません「((37 37)(39 39)(38 38 38 38)(40 40)) – uselpa

+3

[group-by](https://docs.racket-lang.org/reference/pairs.html?q=group#%28def._%28%28lib._racket%2Flist..rkt%29)を使用できます。 _group-by%29%29): '(グループ別ID '(37 37 39 38 38 39 38 40 40 38))'。 – assefamaru

答えて

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