下面的代码成功编译,但在使用GHC 9.2.3和
-Wredundant-constraints
时会收到警告:{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}
class Functor f => C f where c :: f Int
instance (Functor f, Applicative f) => C f where c = pure 42
导致的警告:
test.hs:5:10: warning: [-Wredundant-constraints]
• Redundant constraint: Functor f
• In the instance declaration for ‘C f’
|
5 | instance (Functor f, Applicative f) => C f where c = pure 42
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
然而,如果我移除这个约束条件,代码将无法通过类型检查:
test.hs:5:10: error:
• Could not deduce (Functor f)
arising from the superclasses of an instance declaration
from the context: Applicative f
bound by the instance declaration at test.hs:5:10-29
Possible fix:
add (Functor f) to the context of the instance declaration
• In the instance declaration for ‘C f’
|
5 | instance Applicative f => C f where c = pure 42
| ^^^^^^^^^^^^^^^^^^^^
这使我感到困惑。
这个约束条件真的是多余的吗?或者说它实际上是必需的?
直觉上,我会说它是多余的,因为它已经被Applicative f
隐含了!但 GHC 对此持不同意见,所以我不确定。