【发布时间】:2014-01-09 20:24:31
【问题描述】:
你好,我是一个haskell编程的新手,我写了这段代码:
f :: a->Bool
f x = True
g :: a->Bool
g x = False
class P a where
func :: a->Bool
instance P Integer where
func x = f x
instance P Float where
func x = g x
如果我将函数 func 称为 func 23.3 Ghci 将返回以下错误:
<interactive>:6:6:
Ambiguous type variable a0' in the constraints:
(Fractional a0)
arising from the literal 23.3' at <interactive>:6:6-9
(P a0) arising from a use of func' at <interactive>:6:1-4
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of func', namely 23.3'
In the expression: func 23.3
In an equation for it': it = func 23.3
如果我使用整数作为参数调用func,代码工作正常。如果我用Double 实例替换P 的Float 实例,则代码在调用func 23.3 时可以正常工作。为什么?
【问题讨论】:
-
注意there's no real reason to ever use
Floatin Haskell,所以实际上你应该用Double替换实例,不管这个单态限制的麻烦。
标签: class haskell types double