让我们考虑以下示例:
data A = A{x::Int} deriving(Show)
instance Func_f (A -> String) where
f _ = "ala"
class Func_f a where
f :: a
main :: IO ()
main = do
let
a = A 5
x = f a
print 5
编译ghc -XFlexibleInstances main.hs
(我试过了-XExtendedDefaultRules
,但没有任何进展)
为什么编译时出现错误?:
main.hs:25:21:
No instance for (Func_f (A -> t0)) arising from a use of `f'
The type variable `t0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there is a potential instance available:
instance Func_f (A -> String) -- Defined at main.hs:7:10
Possible fix: add an instance declaration for (Func_f (A -> t0))
In the expression: f a
In an equation for `x': x = f a
In the expression:
do { let a = A 5
x = f a;
print 5 }
Func_f 只有一个实例,所以 Haskell 应该能够知道x = f a
. 您可以通过手动提供类型来修复错误,例如:x = f a :: String
,但这不适合我的情况,因为我正在生成 Haskell 代码,我希望 Haskell 的类型推断器为我完成这项工作。