Skip to content

Instantly share code, notes, and snippets.

@rplevy
Created February 5, 2011 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rplevy/812656 to your computer and use it in GitHub Desktop.
Save rplevy/812656 to your computer and use it in GitHub Desktop.
partitions
(defn split-from
"like split-at but with an offset.
Usage:
(split-from 5 7 (range 10)) -->
[(5 6 7) (8 9)]
"
[offset to s]
(split-at (- to (dec offset))
(second (split-at offset s))))
(defn partitions
"partition a seq using a vector of cut points
Usage:
(partitions [4 7 14] (range 20)) -->
((0 1 2 3 4) (5 6 7) (8 9 10 11 12 13 14) (15 16 17 18 19))
"
([cuts s]
(partitions cuts s 0))
([cuts s offset]
(cond
(and (first cuts) s)
(lazy-seq
(let [divided (split-from offset (first cuts) s)
next-offset (+ offset (count (first divided)))]
(cons (first divided)
(partitions (next cuts) s next-offset))))
:else
(seq [(second (split-at offset s))]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment