Reputation: 31
I've been trying to get a list of lists from a list of lists of ints for example:
[[0,0,1,4,7,10,11,12,16],[1,4,4,6,7,7,12,12,19],[0,0,0,2,4,7,11,12,13]]
should yield [[0,1,0],[0,4,0],[1,4,0]
..and so on]
I can get [0,1,0]
using
map head saidList
And so I've been trying then to use that on the tail of the lists but I can't figure it out.
Any help would be hugely appreciated because this is the final and very small part of a huge project.
Upvotes: 3
Views: 1725
Reputation: 5173
Your approach
map head l
only produces the first list and only works if all lists in the original list of lists are not empty.
You need a way to discard empty lists (you do not want to take the head of these), and then a way to apply the same procedure to the tails of the non-null lists. Here is a possible solution:
filterNonNull x = filter (\y -> not (null y)) x
f x = if null h then [] else h : t
where
n = filterNonNull x
h = (map head n)
t = f (map tail n)
I tested it on ghci:
f [[1, 2, 3], [4, 5, 6],[7,8]]
gives
[[1,4,7],[2,5,8],[3,6]]
Upvotes: 3
Reputation: 183873
Look into Data.List
ghci> :t Data.List.transpose
Data.List.transpose :: [[a]] -> [[a]]
ghci> Data.List.transpose [[0,0,1,4,7,10,11,12,16],[1,4,4,6,7,7,12,12,19],[0,0,0,2,4,7,11,12,13]]
[[0,1,0],[0,4,0],[1,4,0],[4,6,2],[7,7,4],[10,7,7],[11,12,11],[12,12,12],[16,19,13]]
Upvotes: 9