Function split list to lists of length n.


/ Published in: Scheme
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.