为什么这不是一个正确的实现?Monad绑定坚持不同的类型?
instance Monad Lock where
(Working False x) >>= _ = Working False x
(Working True x) >>= f = f x
GHC吐出来的误差约为刚性类型的变量之一:
• Couldn't match type ‘a’ with ‘b’
‘a’ is a rigid type variable bound by
the type signature for:
(>>=) :: forall a b. Lock a -> (a -> Lock b) -> Lock b
at src/Computers.hs:32:22
‘b’ is a rigid type variable bound by
the type signature for:
(>>=) :: forall a b. Lock a -> (a -> Lock b) -> Lock b
at src/Computers.hs:32:22
Expected type: Lock b
Actual type: Lock a
我可能误解了错误,但是从我有限的了解,编译器实际上需要我吐出不同的参数化类型,而不是相同的类型。
我尝试添加不同的构造不带类型参数(和改变只是为了测试语义) - 然后正常工作:
instance Monad Lock where
Broken >>= _ = Broken
(Working False x) >>= _ = Broken
(Working True x) >>= f = f x
编辑: 的确,锁定的定义是:
data Lock a = Working Bool a
包含'Lock'的定义。 –