我正在尝试合并两个列表并删除重复项。以下是我的代码,但我认为我有语法错误,并且任何人都可以提出更好的方法来实现此目的,因为我确信有更好的方法。
我的代码
combine :: [Int] -> [Int] -> [Int]
combine (x:xs++y:ys)
|elem x xs || elem x ys = combine xs ++ ys
|elem y xs || elem y ys = combine xs ++ ys
|otherwise x:y:combine xs ys
我知道问题要我做什么,我知道如何解决它,但我无法克服语法。任何帮助将不胜感激
最佳答案
问题是您已将组合的类型定义为采用两个整数列表并返回一个整数列表,但您将组合定义为采用两个列表的组合。我还相信否则需要 =
combine :: [Int] -> [Int] -> [Int]
combine x y
| null x && not (null y) = y
| null y && not (null x) = x
| null x && null y = []
| elem (head x) (tail x) || elem (head x) (tail y) = combine (tail x) y
| elem (head y) (tail x) || elem (head y) (tail y) = combine x (tail y)
| (head x) == (head y) = (head x) : combine (tail x) (tail y)
| otherwise = (head x) : (head y) : combine (tail x) (tail y)
这听起来像是有更好的方法。某处可能有性能增益(使用 elem 多次扫描列表,我正在看着你)。这段代码看起来也做了很多重复。
更简单的方法是使用 Data.List 中的 nub 函数。
import Data.List { nub }
combine:: [Int] -> [Int] -> [Int]
combine x y = nub (x ++ y)
短暂的cabal 安装 data-ordlist
后:
import Data.List.Ordered
combine x y = nubSort $ x ++ y
运行速度更快。哇!
关于haskell - 合并具有独特元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26829116/