[Haskell-cafe] Nested Lists

Henning Thielemann lemming at henning-thielemann.de
Thu Jun 4 10:54:44 EDT 2009


On Thu, 4 Jun 2009, Paul Keir wrote:

> 
> Hi all,
> 
> If I have a list, and I'd like to convert it to a list of lists,
> each of length n, I can use a function like bunch:
> 
> bunch _ [] = []
> bunch n as = let (c,cs) = splitAt n as in c:bunch n cs

http://hackage.haskell.org/packages/archive/utility-ht/0.0.5.1/doc/html/Data-List-HT.html#v%3AsliceVertical

> > bunch 8 [1..16]
> [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]
> 
> If I now want to do the same for the nested lists, I can compose
> an application involving both map and bunch:
> 
> > map (bunch 4) . bunch 8 $ [1..16]
> [[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]]]
> 
> and I can "bunch" the new length 4 lists again:
> 
> > map (map (bunch 2)) . map (bunch 4) . bunch 8 $ [1..16]
> [[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]]

Don't you first break the list into 2-element lists, then the resulting 
list into 2-element lists and so on? I.e.

bunch 2 . bunch 2 . bunch 2 $ [1..16]


Calling 'bunch' multiple times is problematic since every call has a 
different signature, a different depth of list nesting. I guess you have 
to use a tree type, which allows arbitrary list nesting at run-time.


More information about the Haskell-Cafe mailing list