Can't figure out how to merge two lists in the following way in Haskell:
INPUT: [1,2,3,4,5] [11,12,13,14]
OUTPUT: [1,11,2,12,3,13,4,14,5]
This would work similar to shuffling a deck of cards. Thanks in advance.
Can't figure out how to merge two lists in the following way in Haskell:
INPUT: [1,2,3,4,5] [11,12,13,14]
OUTPUT: [1,11,2,12,3,13,4,14,5]
This would work similar to shuffling a deck of cards. Thanks in advance.
merge :: [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : merge xs ys
EDIT: Take a look at Ed'ka's answer and comments!
Another possibility:
merge xs ys = concatMap (\(x,y) -> [x,y]) (zip xs ys)
Or, if you like Applicative:
merge xs ys = concat $ getZipList $ (\x y -> [x,y]) <$> ZipList xs <*> ZipList ys
So why do you think that simple (concat . transpose) "is not pretty enough"? I assume you've tried something like:
merge :: [[a]] -> [a]
merge = concat . transpose
merge2 :: [a] -> [a] -> [a]
merge2 l r = merge [l,r]
Thus you can avoid explicit recursion (vs the first answer) and still it's simpler than the second answer. So what are the drawbacks?
I want to propose a lazier version of merge:
merge [] ys = ys
merge (x:xs) ys = x:merge ys xs
For one example use case you can check a recent SO question about lazy generation of combinations.
The version in the accepted answer is unnecessarily strict in the second argument and that's what is improved here.