将列表与唯一元素合并

时间:2014-11-09 14:14:21

标签: haskell

我正在尝试组合两个列表并删除重复项。以下是我的代码,但我认为我有语法错误,也可以有人建议更好的方法来实现这一点,因为我相信有更好的方法。

我的代码

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

我知道问题要我做什么,我知道如何解决它,但我无法克服语法。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

问题是你已经将组合的类型定义为获取两个整数列表并返回一个整数列表,但是您将组合定义为采用两个列表的组合。另外我认为否则需要=

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 install data-ordlist

import Data.List.Ordered
combine x y = nubSort $ x ++ y

运行得更快。凌晨!