1
votes

I am trying to build a function which works on lists of lists. This function would take the 1rst element of each list inside the big list, put them into a list together, then do this for the 2nd element, etc. Ex:

tr[[1,2,3],[4,5,6]]    
=> [[1,4],[2,5],[3,6]

It can work for any data type, but for now I am trying to make it work for Int

Here is what I have so far, just the data declaration and a case for empty input:

tr :: [[a]] -> [[a]]

tr [] = []

Any help is much appreciated, or even a pointer to a place with information. My idea is that it will use the ++ operator, and the x:xs manipulation of List elements. My problem is figuring out how to access the head of each list respectively, and not just the first list. I can get the 1 from the example using: head $ head [[1,2,3]].

1
So you're trying to transpose a list of lists?Eli Sadoff
It might be worthwhile looking at this, which does exactly what you wantEli Sadoff
@EliSadoff yes actually it is transposition, I did not see that it was! Thanks :)Demostroyer
No worries! Hoogle is an awesome resource.Eli Sadoff
I can recommend haskellbook.comM.K.

1 Answers

0
votes

Comments answer your question. But, a more generic/abstract version would be one which works with any Foldable data structure, not only lists. That can be done with nested right folds:

import Prelude hiding (foldr)  -- older version ghc
import Data.Foldable (foldr, Foldable)

tr :: (Foldable f, Foldable s) => f (s a) -> [[a]]
tr = takeWhile (not . null) . foldr (foldr go id) (repeat [])
  where go i f (x:xs) = (i:x): f xs

then:

\> tr [[10,11],[20],[],[30,31,32]] 
[[10,20,30],[11,31],[32]]

\> tr [Just 1, Nothing, Just 2]
[[1,2]]