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 に答える