2

如何合并元组列表而不重复这些元组中的任何项目?

例如 :

从列表 [("a","b"),("c,"d"),("a","b)] 中,它应该返回 ["a","b","c"," d"]


所以我用该代码收到此错误消息:

No instance for (Eq a0) arising from a use of `nub'
The type variable `a0' is ambiguous
Possible cause: the monomorphism restriction applied to the following:
  merge :: [(a0, a0)] -> [a0] (bound at P.hs:9:1)
Probable fix: give these definition(s) an explicit type signature
              or use -XNoMonomorphismRestriction
Note: there are several potential instances:
  instance Eq a => Eq (GHC.Real.Ratio a) -- Defined in `GHC.Real'
  instance Eq () -- Defined in `GHC.Classes'
  instance (Eq a, Eq b) => Eq (a, b) -- Defined in `GHC.Classes'
  ...plus 22 others
In the first argument of `(.)', namely `nub'
In the expression: nub . mergeTuples
In an equation for `merge':
    merge
      = nub . mergeTuples
      where
          mergeTuples = foldr (\ (a, b) r -> a : b : r) []

失败,加载模块:无。

4

1 回答 1

4

让我们把它分开,首先,合并元组

mergeTuples :: [(a, a)] -> [a]
mergeTuples = concatMap (\(a, b) -> [a, b]) -- Thanks Chuck
-- mergeTuples = foldr (\(a, b) r -> a : b : r) []

然后我们可以用nub它来使它独一无二

merge :: Eq a => [(a, a)] -> [a]
merge = nub . mergeTuples

如果你想让这一切都在一起

merge = nub . mergeTuples
  where mergeTuples = concatMap (\(a, b) -> [a, b])

或者,如果您想将它真正粉碎在一起(不要这样做)

merge [] = []
merge ((a, b) : r) = a : b : filter (\x -> x /= a && x /= b) (merge r)
于 2013-10-24T18:04:51.973 回答