这个问题在这里已经有了答案:
Merging two lists in Haskell
(6 个回答)
6年前关闭。
我只是在学习 Haskell,我想制作一个“洗牌”功能,将两个列表混在一起,交替直到一个列表用完。所以,shuffle "abc" "defgh"
会返回 "adbecfgh"
.或 shuffle "abc" ""
返回 "abc"
.
到目前为止,我有:
shuffle xs ys = concatMap (\(x,y) -> [x,y]) (zip xs ys)
问题在于它只是根据最短列表的长度对列表进行混洗,而不包括较长列表的其余部分。所以
shuffle "abc" "defgh"
返回 "adbecf"
而不是 "adbecfgh"
.谁能帮我找到更好的方法?
最佳答案
您可以简单地提供一个逐点定义:
shuffle :: [a] -> [a] -> [a]
shuffle [] ys = ys
shuffle xs [] = xs
shuffle (x:xs) (y:ys) = x : y : shuffle xs ys
每
zip*
Prelude
中的方法或 Data.List
不会起作用,因为它们只会占用较短列表的长度。
关于haskell - 在 Haskell 中将两个列表混在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28448321/