我有两个模块定义如下:
Foo.hs
module Foo
where
class F t where
c :: t -> Char
instance F Double where
c s = 'x'
Main.hs
import Foo
main :: IO ()
main = do
print $ (c 2.0)
当我编译这两个模块时,我得到了这个错误:
ghc Foo.hs Main.hs
[1 of 2] Compiling Foo ( Foo.hs, Foo.o )
[2 of 2] Compiling Main ( Main.hs, Main.o )
Main.hs:6:12: error:
• Ambiguous type variable ‘t0’ arising from a use of ‘c’
prevents the constraint ‘(F t0)’ from being solved.
Probable fix: use a type annotation to specify what ‘t0’ should be.
These potential instance exist:
instance [safe] F Double -- Defined in ‘Foo’
• In the second argument of ‘($)’, namely ‘(c 2.0)’
In a stmt of a 'do' block: print $ (c 2.0)
In the expression: do { print $ (c 2.0) }
Main.hs:6:14: error:
• Ambiguous type variable ‘t0’ arising from the literal ‘2.0’
prevents the constraint ‘(Fractional t0)’ from being solved.
Probable fix: use a type annotation to specify what ‘t0’ should be.
These potential instances exist:
instance Fractional Double -- Defined in ‘GHC.Float’
instance Fractional Float -- Defined in ‘GHC.Float’
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘c’, namely ‘2.0’
In the second argument of ‘($)’, namely ‘(c 2.0)’
In a stmt of a 'do' block: print $ (c 2.0)
如何解决此问题,以便打印出'x'?
答案 0 :(得分:3)
您应该将evaluate
重命名为call
。
编辑:尝试将c
注释为2.0
:
Double
GHC不知道print $ c (2.0 :: Double)
使用哪种类型,它可以是任何2.0
类型。要解决此问题,我们会通过明确标记其类型来强制Fractional
为2.0
类型。