Reputation: 61041
How to solve this problem?
The problem is to reorder the list-of-lists of doubles:
[ [a, b, c], [aa, bb, cc] ]
into this:
[ [a, aa], [b, bb], [c, cc] ]
After poking about I came up with the following (a function that increasingly diggs deeper and deeper into sublists, taking their head
and joining them together):
organize xs = organize' xs head
--recursive function (type stolen from ghci)
organize':: [[a]] -> ([a] -> b) -> [b]
organize' [] f = []
organize' xs f = (map f xs)++(organize' xs (f . tail)
This doesn't work too good (which I thought it did) - in my joy of success I completely missed the error:
Exception: Prelude.head: empty list
Upvotes: 1
Views: 127
Reputation: 1935
Your mention of "doubles" implies that you want a list of 2-tuples (ie, "doubles"), rather than a list of 2-element lists. (Or perhaps this wording was particular to my Function Programming 101 lecturer!)
In which case, zip
does exactly this:
zip [1, 2, 3] [4, 5, 6] = [(1,4),(2,5),(3,6)]
If you do need a list of 2-element lists (instead of tuples), you can use zipWith:
organize [xs,ys] = zipWith (\x y -> [x,y]) xs ys
Or are you looking for something that will work with any number of lists? In that case (as others have commented) transpose
from Data.List is what you're after:
transpose [[1,2,3],[4,5,6]] = [[1,4],[2,5],[3,6]]
Upvotes: 2