Skip to content

Instantly share code, notes, and snippets.

@takikawa
Created August 3, 2012 20:01
Show Gist options
  • Save takikawa/3250962 to your computer and use it in GitHub Desktop.
Save takikawa/3250962 to your computer and use it in GitHub Desktop.
group
#lang racket
;; splits the list into groups of n or less
;; nat (listof x) -> (listof (listof x))
(define (group n lst)
(let loop ([lst lst] [acc '()])
(if (null? lst)
(reverse acc)
(loop (drop-up-to lst n)
(cons (take-up-to lst n) acc)))))
;; take n if available, otherwise all
;; (listof x) nat -> (listof x)
(define (take-up-to lst n)
(if (< (length lst) n)
lst
(take lst n)))
;; drop n if available, otherwise none
;; (listof x) nat -> (listof x)
(define (drop-up-to lst n)
(if (< (length lst) n)
null
(drop lst n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment