Merging two lists in Haskell

68,562

Solution 1

merge :: [a] -> [a] -> [a]
merge xs     []     = xs
merge []     ys     = ys
merge (x:xs) (y:ys) = x : y : merge xs ys

Solution 2

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.

Solution 3

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?

Solution 4

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

Solution 5

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))
Share:
68,562
bogatyrjov
Author by

bogatyrjov

Updated on July 21, 2022

Comments

  • bogatyrjov
    bogatyrjov almost 2 years

    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]