data Set a = Set [a]
i1 = Set [1, 2, 3]
i2 = Set [3, 2, 1]
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 Eq 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"
执行时:cmp i1 i2
我收到以下错误:
No instance for (Comparable Integer) arising from a use of ‘cmp’
In the expression: cmp i1 i2
In an equation for ‘it’: it = cmp i1 i2
我想知道这意味着什么? 感谢。
答案 0 :(得分:0)
执行时:
cmp i1 i2
Haskell将i1
和i2
的类型推断为Set [Integer]
。由于cmp
的类型为:
cmp :: (Comparable a) => a -> a -> String
Integer
必须有Comparable
类型的实例;它没有。因此,要解决此问题,您应为Comparable
提供Integer
的实例。
另请注意,您可能需要使用Ord
来定义不同类型的值之间的比较。