Merging two lists in Haskell

前端 未结 6 1532
轮回少年
轮回少年 2020-11-29 09:26

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]         


        
相关标签:
6条回答
  • 2020-11-29 09:38

    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.

    0 讨论(0)
  • 2020-11-29 09:45

    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))
    
    0 讨论(0)
  • 2020-11-29 09:56
    -- ++
    pp [] [] = []
    pp [] (h:t) = h:pp [] t
    pp (h:t) [] = h:pp t []
    pp (h:t) (a:b) = h : pp t (a:b)
    
    0 讨论(0)
  • 2020-11-29 09:59
    merge :: [a] -> [a] -> [a]
    merge xs     []     = xs
    merge []     ys     = ys
    merge (x:xs) (y:ys) = x : y : merge xs ys
    
    0 讨论(0)
  • 2020-11-29 09:59

    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?

    0 讨论(0)
  • 2020-11-29 10:01

    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
    
    0 讨论(0)
提交回复
热议问题