PasteRack.org
Paste # 43700
2017-03-21 20:11:10

Forked from paste # 35007.

Fork as a new paste.

Paste viewed 99 times.


Embed:

chunk-list

  1. #lang racket
  2.  
  3. ;; Split a list into ct chunks as best you can
  4. ;; ex: (chunk-list (range 0 12) 3) -> '((0 1 2 3) (4 5 6 7) (8 9 10 11 12))
  5. (define (chunk-list ls ct)
  6.   (define n (round (/ (length ls) ct)))
  7.   (define (loop ls ct ac)
  8.     (cond [(empty? ls)
  9.            (reverse ac)]
  10.           [(< (length ls) n)
  11.            (if (equal? (length ac) ct)
  12.                (reverse (cons (flatten (append (take ac 1) ls))
  13.                               (drop ac 1)))
  14.                (reverse (cons ls ac)))]
  15.           [else
  16.            (loop (drop ls n) ct (cons (take ls n) ac))]))
  17.   (loop ls ct '()))
  18.  
  19. (define xs (range 0 13))
  20.  
  21. (chunk-list xs 3)

=>

'((0 1 2 3) (4 5 6 7) (8 9 10 11 12))