考虑以下:
{-# LANGUAGE FlexibleContexts #-}
module Foo where
data D a = D a
class Foo b
instance (Num a) => Foo (D a)
f :: (Foo (D a)) => a -> a
f x = x+1
GHC 提示无法推断
Num a
在 f
.我希望从 Foo
的(非重叠)实例中推断出这个约束。对于 D a
.我知道我可以将 GADT 用于
D
并添加约束 Num a
在那里,但我希望不必污染 D
的构造函数有很多不必要的限制。有没有希望发生这种情况,现在有可能吗?
最佳答案
我猜这会因重叠实例而中断,因此一般不会推断。也就是说,你可以有
{-# LANGUAGE OverlappingInstances #-}
...
instance (Num a) => Foo (D a)
instance Foo (D Bool)
那么你想要的推论肯定不会是正确的。
编辑:更仔细地查看 the documentation , 有可能有
{-# LANGUAGE FlexibleContexts #-}
module Foo where
data D a = D a
class Foo b
instance (Num a) => Foo (D a)
f :: (Foo (D a)) => a -> a
f x = x+1
然后在一个单独的文件中:
{-# LANGUAGE OverlappingInstances #-}
module Bar where
import Foo
instance Foo Bool
test = f True
也就是说,文档暗示只有定义两个实例的模块之一需要具有
OverlappingInstances
标志,所以如果 Foo.f
可以这样定义,您可以制作另一个模块 Bar
完全破坏类型安全。请注意,使用 GHC 的单独编译,f
将在不了解模块 Bar
的情况下完全编译.
关于haskell - 来自实例的约束推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830462/