考虑以下(接近最小)示例:
{-# Language FlexibleInstances #-}
class Predicate a where
test :: a -> Bool
instance (Predicate a, Traversable t) => Predicate (t a) where
test = all test
data Bar = Bar
instance Predicate Bar where
test Bar = False
data Baz a = Baz a
instance Predicate a => Predicate (Baz a) where
test (Baz x) = test x
main :: IO ()
main = print $ test $ Baz Bar
看着test $ Baz Bar
,您会期望得到 的结果False
,因为我们有实例Predicate Bar
和Predicate a => Predicate (Baz a)
。
但是 GHC 8.6.3 和 8.0.1 都拒绝这个:
test.hs:18:16: error:
• Overlapping instances for Predicate (Baz Bar)
arising from a use of ‘test’
Matching instances:
instance (Predicate a, Traversable t) => Predicate (t a)
-- Defined at test.hs:6:10
instance Predicate a => Predicate (Baz a)
-- Defined at test.hs:14:10
• In the second argument of ‘($)’, namely ‘test $ Baz Bar’
In the expression: print $ test $ Baz Bar
In an equation for ‘main’: main = print $ test $ Baz Bar
|
18 | main = print $ test $ Baz Bar
| ^^^^^^^^^^^^^^
然而没有重叠:我们可以Traversable Baz
通过注释掉实例来确认没有Predicate (Baz a)
实例,在这种情况下我们会得到错误:
test.hs:18:16: error:
• No instance for (Traversable Baz) arising from a use of ‘test’
• In the second argument of ‘($)’, namely ‘test $ Baz Bar’
In the expression: print $ test $ Baz Bar
In an equation for ‘main’: main = print $ test $ Baz Bar
|
18 | main = print $ test $ Baz Bar
| ^^^^^^^^^^^^^^
我假设这是一个限制FlexibleInstances
?如果是这样,为什么,是否有批准的解决方法?
好的,事实证明这是 GHC 决定使用哪个实例而不受实例约束的结果,如此处所述。不过,这个技巧在这里似乎不起作用:
instance (b ~ Baz, Predicate a) => Predicate (b a) where
给出一个Duplicate instance declarations
错误,所以我将这个问题留给在这种情况下有效的解决方案。