list 在 Haskell 中合并两个列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3938438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merging two lists in Haskell
提问by bogatyrjov
Can't figure out how to merge two lists in the following wayin Haskell:
无法弄清楚如何在 Haskell中以下列方式合并两个列表:
INPUT: [1,2,3,4,5] [11,12,13,14]
OUTPUT: [1,11,2,12,3,13,4,14,5]
回答by Daniel Velkov
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.
对于一个示例用例,您可以查看最近关于延迟生成组合的SO 问题。
接受的答案中的版本在第二个参数中不必要地严格,这就是这里的改进。
回答by andri
merge :: [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : merge xs ys
回答by Ed'ka
So why do you think that simple (concat . transpose) "is not pretty enough"? I assume you've tried something like:
那么为什么你认为简单的 (concat . transpose) “不够漂亮”?我假设你已经尝试过类似的事情:
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?
因此,您可以避免显式递归(与第一个答案相比),并且它仍然比第二个答案简单。那么有什么缺点呢?
回答by danlei
EDIT: Take a look at Ed'ka's answer and comments!
编辑:看看 Ed'ka 的回答和评论!
Another possibility:
另一种可能:
merge xs ys = concatMap (\(x,y) -> [x,y]) (zip xs ys)
Or, if you like Applicative:
或者,如果您喜欢 Applicative:
merge xs ys = concat $ getZipList $ (\x y -> [x,y]) <$> ZipList xs <*> ZipList ys
回答by idontgetoutmuch
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))
回答by Dormenco Ion
-- ++
pp [] [] = []
pp [] (h:t) = h:pp [] t
pp (h:t) [] = h:pp t []
pp (h:t) (a:b) = h : pp t (a:b)