"No instance for (Comparable Integer)" 是什么意思?
What does "No instance for (Comparable Integer)" mean?
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
我想知道这是什么意思?
谢谢
当您执行时:
cmp i1 i2
Haskell 推断 i1
和 i2
的类型为 Set [Integer]
。由于 cmp
具有类型:
cmp :: (Comparable a) => a -> a -> String
Integer
必须有一个 Comparable
类型的实例 class;它没有。因此,要解决此问题,您应该为 Integer
.
提供 Comparable
的实例
另请注意,您可能打算使用 Ord
来定义不同类型值之间的比较。
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
我想知道这是什么意思? 谢谢
当您执行时:
cmp i1 i2
Haskell 推断 i1
和 i2
的类型为 Set [Integer]
。由于 cmp
具有类型:
cmp :: (Comparable a) => a -> a -> String
Integer
必须有一个 Comparable
类型的实例 class;它没有。因此,要解决此问题,您应该为 Integer
.
Comparable
的实例
另请注意,您可能打算使用 Ord
来定义不同类型值之间的比较。