2017-11-17 2 views
-1

Wenn eine Liste erstellt wird, muss ich die Liste in Listen aufteilen, die die gleichen Elemente gruppieren.Gruppennummern in einer Liste im Schema?

Zum Beispiel: '(37 37 39 38 38 39 38 40 40 38) in zur Folge' ((37 37) (39 39) (38 38 38 38) (40 40))

Can jemand mir dabei helfen?

+0

Das Ergebnis sollte sein ‚((37 37) (39 39) (38 38 38 38) (40 40)) – uselpa

+3

Sie können [group-by] (https://docs.racket-lang.org/reference/pairs.html?q=group#%28def._%28%28lib._racket%2Flist..rkt%29) verwenden. _group-by% 29% 29): "(nach Identität" (37 37 39 38 38 39 38 40 40 38)) ". – assefamaru

Antwort

0

Hier ist eine Möglichkeit, es zu tun:

(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 

Testing

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