Skip to content

Instantly share code, notes, and snippets.

@yuga
Last active August 29, 2015 14:08
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 yuga/358fa824e95a3eb17f69 to your computer and use it in GitHub Desktop.
Save yuga/358fa824e95a3eb17f69 to your computer and use it in GitHub Desktop.
-- > chunkGroupBy (\x y -> x == y) 6 [0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,3]
-- [[[0,0,0,0]],[[1,1,1]],[[2,2,2,2,2]],[[3,3,3,3]]]
--
-- > chunkGroupBy (\x y -> x == y) 7 [0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,3]
-- [[[0,0,0,0],[1,1,1]],[[2,2,2,2,2]],[[3,3,3,3]]]
--
-- > chunkGroupBy (\x y -> x == y) 15 [0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,3]
-- [[[0,0,0,0],[1,1,1],[2,2,2,2,2]],[[3,3,3,3]]]
--
-- > chunkGroupBy (\x y -> x == y) 16 [0,0,0,0,1,1,1,2,2,2,2,2,3,3,3,3]
-- [[[0,0,0,0],[1,1,1],[2,2,2,2,2],[3,3,3,3]]]
--
chunkGroupBy :: (Num n, Ord n) => (a -> a -> Bool) -> n -> [a] -> [[[a]]]
chunkGroupBy eq n as = chunk $ groupBy eq as
where
chunk [] = []
chunk (x:xs) = (x:ys):chunk zs
where (ys,zs) = spanOrd (len x) xs
spanOrd _ xs@[] = (xs,xs)
spanOrd cnt xs@(x:xs')
| cnt' <= n = let (ys,zs) = spanOrd cnt' xs' in (x:ys,zs)
| otherwise = ([],xs)
where cnt' = cnt + len x
len = genericLength
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment