[Haskell-cafe] Nested Lists

Emil Axelsson emax at chalmers.se
Thu Jun 4 08:26:58 EDT 2009


Hi Paul,

I don't have time to solve your actual problem, but I think it's doable 
using associated type families. I attach a module which I'm using in my 
current project that does things quite similar to what you're asking for.

For example:

   *Main> replicateArray (3 :> IntArr) 4
   [4,4,4]

   *Main> replicateArray (4 :> 3 :> IntArr) 4
   [[4,4,4],[4,4,4],[4,4,4],[4,4,4]]

Hope it helps!

/ Emil



Paul Keir skrev:
> 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
> 
>  > 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]]]]
> 
> Clearly there is a pattern here involving the bunch function and
> latterly, three Int parameters; 2, 4 and 8. My question is, can I
> create a function that will take such parameters as a list, and
> give the same result, for example:
> 
>  > f [2,4,8] [1..16]
> [[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]]
> 
> or perhaps:
> 
>  > f [bunch 2, bunch 4, bunch 8] [1..16]
> [[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]]
> 
> I think it may not be possible because the type signature of f would
> depend on the length of its list parameter; but I'm not sure.
> 
> -Paul
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Bunch.hs
Type: text/x-haskell
Size: 1061 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20090604/45a3895c/Bunch.bin


More information about the Haskell-Cafe mailing list