list - Nested chunksOf in Haskell? -
say want this:
nestedchunksof [3, 2] [1,1,1,2,2,2,3,3,3,4,4,4] == [[[1,1,1], [2,2,2]], [[3,3,3], [4,4,4]]] in python, can this
def group(a, *ns): n in ns: = [a[i:i+n] in xrange(0, len(a), n)] return group([1,1,1,2,2,2,3,3,3,4,4,4], 3, 2) == [[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]] but in haskell, can't say
nestedchunksof :: [int] -> [a] -> [[a]] or
nestedchunksof :: [int] -> [a] -> [[[a]]] so how can achieve same thing in haskell?
it can done dependent types.
we'd express length of [int] argument determines type of result. need 2 things that: list type fixed length, , type-level function computes return type length:
{-# language datakinds, gadts, typefamilies #-} import data.list.split data nat = z | s nat -- natural numbers (zero, successor) data vec n -- "n" length lists of "a" elements nil :: vec z (:>) :: -> vec n -> vec (s n) infixr 5 :> type family iterate n f iterate z f = iterate (s n) f = f (iterate n f a) iterate n f a applies type constructor f n times argument. example, iterate (s (s z)) [] int reduces [[int]]. nestedchunksof can written directly now:
nestedchunksof :: vec n int -> [a] -> iterate (s n) [] nestedchunksof nil = nestedchunksof (n :> ns) = chunksof n $ nestedchunksof ns usage:
> nestedchunksof (2 :> 3 :> nil) [1,1,1,2,2,2,3,3,3,4,4,4] [[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]]
Comments
Post a Comment