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]
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.
Surely a case for an unfold:
interleave :: [a] -> [a] -> [a]
interleave = curry $ unfoldr g
where
g ([], []) = Nothing
g ([], (y:ys)) = Just (y, (ys, []))
g (x:xs, ys) = Just (x, (ys, xs))
-- ++
pp [] [] = []
pp [] (h:t) = h:pp [] t
pp (h:t) [] = h:pp t []
pp (h:t) (a:b) = h : pp t (a:b)
merge :: [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : merge xs 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?
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