在Haskell中合并两个列表

时间:2010-10-14 23:48:31

标签: list haskell merge functional-programming interleave

无法弄清楚如何在Haskell中以下列方式合并两个列表

INPUT:  [1,2,3,4,5] [11,12,13,14]

OUTPUT: [1,11,2,12,3,13,4,14,5]

6 个答案:

答案 0 :(得分:54)

我想提出一个更加懒惰的合并版本:

merge [] ys = ys
merge (x:xs) ys = x:merge ys xs

对于一个示例用例,您可以查看最近有关lazy generation of combinations的SO问题 接受的答案中的版本在第二个参数中是不必要的严格,这是在这里改进的。

答案 1 :(得分:42)

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

答案 2 :(得分:23)

那你为什么认为那么简单(concat.transpose)“还不够”?我假设你尝试过类似的东西:

merge :: [[a]] -> [a]
merge = concat . transpose

merge2 :: [a] -> [a] -> [a]
merge2 l r = merge [l,r]

因此,您可以避免显式递归(与第一个答案相比),但仍然比第二个答案更简单。那有什么缺点呢?

答案 3 :(得分:6)

编辑:看看Ed'ka的回答和评论!

另一种可能性:

merge xs ys = concatMap (\(x,y) -> [x,y]) (zip xs ys)

或者,如果你喜欢Applicative:

merge xs ys = concat $ getZipList $ (\x y -> [x,y]) <$> ZipList xs <*> ZipList ys

答案 4 :(得分:4)

肯定是一个展开的案例:

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))

答案 5 :(得分:-2)

-- ++
pp [] [] = []
pp [] (h:t) = h:pp [] t
pp (h:t) [] = h:pp t []
pp (h:t) (a:b) = h : pp t (a:b)