【问题标题】:How can i separate tuples in Haskell?如何在 Haskell 中分离元组?
【发布时间】:2013-10-27 02:11:25
【问题描述】:

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

例如:

从列表 [("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) []

失败,已加载模块:无。

【问题讨论】:

    标签: list haskell


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 是否有可能在一个函数中实现所有功能?
    • @dcarou 当然,在 where 子句中定义 mergeTuple
    • 我该怎么做?而且我无法让这段代码与上面的示例一起使用,它根本无法编译
    • @dcarou 错误信息是什么?告诉我们它不能编译并不能告诉我们为什么它不能编译
    • 只是一个吹毛求疵,但我认为这里的地图比折叠更自然 — mergeTuples = concatMap (\(a,b) -> [a, b])
    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多