【发布时间】:2015-09-13 13:02:52
【问题描述】:
我想知道在 GHCi 中评估表达式 1 .+. 2 时,Haskell 使用什么规则来始终决定 Integer 实例而不是其他实例:
import Debug.Trace
class MyFuns a where
(.+.) :: a → a → a
instance MyFuns Double where
x .+. y = trace "Double " $ x + y
instance MyFuns Integer where
x .+. y = trace "Integer " $ x + y
instance MyFuns Int where
x .+. y = trace "Int " $ x + y
编辑:如果我在文件末尾添加以下代码
main = do
let x = 1 .+. 2
print x
为什么会出现这个错误?
No instance for (Num a0) arising from the literal ‘1’
The type variable ‘a0’ is ambiguous
Relevant bindings include x :: a0 (bound at fun2.hs:19:7)
Note: there are several potential instances:
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in ‘GHC.Real’
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
...plus three others
In the first argument of ‘(.+.)’, namely ‘1’
In the expression: 1 .+. 2
In an equation for ‘x’: x = 1 .+. 2
然而,如果我在没有main = ... 的情况下在 GHCi 提示符处加载文件,然后键入 1 .+. 2,GHCi 会按预期打印 3。为什么会有这种行为?
谢谢
【问题讨论】:
标签: haskell