data Set a = Set [a]
member xs x = elem x xs
subset xs ys = and (map (member ys) xs)

instance (Eq a) => Eq (Set a) where
  (Set xs) == (Set ys) = (subset xs ys) && (subset ys xs)

class Ord a => Comparable a where
  cmp :: a -> a -> String
  cmp x y
    | x == y    = "eq"
    | otherwise = "neq"

instance Comparable a => Comparable (Set a) where
  cmp (Set xs) (Set ys)
    | (Set xs) == (Set ys) = "same"
    | otherwise            = "different"

我收到以下错误:

无法推论(Ord(Set a))
由实例声明的父类(super class)产生
从上下文(可比a)
受“可比较(集合a)”的实例声明约束

我想知道错误是什么?
谢谢。

最佳答案

这个宣言

class Ord a => Comparable a where

声明Comparable类的每个成员都必须是Ord类的成员。如果我要尝试做
data MyType = ...
instance Comparable MyType where
  cmp x y = "hello"

编译器会抱怨缺少实例Ord MyType。我没有使用那个Ord实例中的任何东西都没有关系:Comparable的定义要求它。

要解决此问题,请添加一个实例
instance Ord a => Ord (Set a) where
   compare setA setB = ....

之后,只要将Comparable添加到约束中,就可以使用Ord a实例。
instance (Ord a , Comparable a) => Comparable (Set a) where
  cmp (Set xs) (Set ys)
    | (Set xs) == (Set ys) = "same"
    | otherwise            = "different"

关于haskell - Haskell-编译错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29040400/

10-12 21:41