Haskell类型错误。无法与(Int - > Int)匹配(Bits b => Int - > b)

时间:2014-11-17 18:31:46

标签: haskell typeclass

我有这个简单的代码

class Hashable a where
    hash :: Bits b => a -> b

instance Hashable Int where
    hash = id

但是我收到以下错误

Could not deduce (b ~ Int)
from the context (Bits b)
  bound by the type signature for hash :: Bits b => Int -> b
  at Memo.hs:11:5-8
  `b' is a rigid type variable bound by
      the type signature for hash :: Bits b => Int -> b at Memo.hs:11:5
Expected type: Int -> b
  Actual type: Int -> Int
Relevant bindings include hash :: Int -> b (bound at Memo.hs:11:5)
In the expression: id :: Int -> Int
In an equation for `hash': hash = id :: Int -> Int
In the instance declaration for `Hashable Int'

我真的不明白。该类仅指定您可以从类型为。

的对象获取Bits实例

存在Bits Int,为什么hash = id不适用于Int?

1 个答案:

答案 0 :(得分:6)

(Bits b=>a->b)表示您可以提取任何类型的Bits实例,而不仅仅是一个。 hash = id仅适用于类型Int,编译器基本上抱怨“嘿,所有其他Bits实例怎么样?”