Haskell - 编译错误

Haskell - Compile Error

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)) 源自实例声明的超类 从上下文(比较a) 受“Comparable (Set a)”实例声明的约束

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

ComparableOrd 的子类,因此您需要为 Ord (Set a) 添加一个实例,例如:

instance Ord a => Ord (Set a) where
  compare (Set s1) (Set s2) =
    compare (sort s1) (sort s2)

这个声明

class Ord a => Comparable a where

表示 class Comparable 的每个成员都必须是 class 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"  

您为集合数据类型提供了一个 Equality 实例,但它没有 Ord 实例。当您尝试创建 Comparable class 的 Set 和实例时,它要求 Set 必须是 Ord 的实例。