class (Eq a) => My a where
f:: (a,a) -> (a,a)
instance My Int where
f (a,b) = (a,b)
instance My Char where
f (a,b) = (a,b)和“这对情侣的专长”。它会产生编译错误,我不知道为什么。请帮助修复它,并解释为什么它是错误的。
instance (My a, My b) => My (a,b) where
f ((a,b), (c,d)) = ( (f (a,b)), (f (c,d)) )错误:
test.hs:11:31:
Could not deduce (a ~ b)
from the context (Eq (a, b), My a, My b)
bound by the instance declaration at test.hs:10:10-33
`a' is a rigid type variable bound by
the instance declaration at test.hs:10:10
`b' is a rigid type variable bound by
the instance declaration at test.hs:10:10
Expected type: (a, b)
Actual type: (a, a)
In the return type of a call of `f'
In the expression: (f (a, b))
In the expression: ((f (a, b)), (f (c, d)))
Failed, modules loaded: none.发布于 2016-03-22 00:50:53
错误信息是正确的。在您的元组实例中,
f :: ((a,b), (a,b)) -> ((a,b), (a,b))其中a和b在一般情况下是不同的类型。但是,对于任何实例,f只能对(a,a)元组进行操作,即您需要类型相等的a ~ b。因此
instance (My a) => My (a,a) where
f (ab, cd) = (f ab, f cd)会起作用..。或者,实际上,我记得这导致了一些问题(忘记了什么),您最好将相等约束明确化。
instance (My a, a~b) => My (a,b) where发布于 2016-03-22 08:28:21
您可能需要以下实例:
instance (My a, My b) => My (a,b) where
f ((a, b), (c, d)) = case (f (a, c), f (b, d)) of
((a1, a2), (b1, b2)) -> ((a1, b1), (a2, b2))在(a, c) :: (a, a)和(b, d) :: (b, b)上面,所以我们将f应用于这些。我们得到一对类型的((a, a), (b, b)),我们重新排序,以获得((a, b), (a, b))。
https://stackoverflow.com/questions/36144258
复制相似问题