你好我與Haskell的編程新手,我寫這段代碼:爲什麼程序在double類型下運行良好,而不是float類型?
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
,代碼工作正常。如果我將P的Float
實例替換爲Double
實例,代碼將與呼叫func 23.3
一起正常工作。爲什麼?
請注意,[沒有真正的理由在Haskell中使用'Float'](http://www.haskell.org/haskellwiki/Performance/Floating_point),所以實際上你應該用'Double'代替實例這種單態限制的麻煩。 – leftaroundabout