如何合并元组列表而不重复那些元组中的任何项目?
例如:
从列表[(“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) []
失败,模块加载:无。
答案 0 :(得分: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)