什么"没有(可比较的整数)"意思?

时间:2015-03-13 18:16:47

标签: haskell typeclass

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

我想知道这意味着什么? 感谢。

1 个答案:

答案 0 :(得分:0)

执行时:

cmp i1 i2  

Haskell将i1i2的类型推断为Set [Integer]。由于cmp的类型为:

cmp :: (Comparable a) => a -> a -> String

Integer必须有Comparable类型的实例;它没有。因此,要解决此问题,您应为Comparable提供Integer的实例。

另请注意,您可能需要使用Ord来定义不同类型的值之间的比较。

相关问题