Posted By

jcubic on 08/25/10


Tagged

listgroupsplit


Versions (?)

Function split list to lists of length n.


 / Published in: Scheme
 

Function group-for which return list of list of length n. (group-for '(1 2 3 4 5 6 7 8 9) 3) => ((1 2 3) (4 5 6) (7 8 9))

  1. (define (skip list n)
  2. (cond ((null? list) '())
  3. ((<= n 0) list)
  4. (else
  5. (skip (cdr list) (- n 1)))))
  6.  
  7. (define (splice list n m)
  8. (let loop ((stop (- m n)) (list (skip list n)))
  9. (if (or (eq? stop 0) (null? list))
  10. '()
  11. (cons (car list) (loop (- stop 1) (cdr list))))))
  12.  
  13. (define (group-for list count)
  14. (let ((step (/ (length list) count)))
  15. (let loop ((i 0))
  16. (if (eq? i count)
  17. '()
  18. (cons (splice list (* i count) (* (+ i 1) count))
  19. (loop (+ i 1)))))))

Report this snippet  

You need to login to post a comment.