2016-11-28 69 views
1

我想寫遞歸數函數泰勒:哈斯克爾沒有實例...產生

mcloren x = log (1+x)/(1-x) 

compareWithDelta' :: (Num a, Floating a, Integral a, Ord a) => a -> a -> Bool 
compareWithDelta' x acc = abs (acc - mcloren x) < 1.0e-10 

mcl :: (Floating a, Integral a, Num a) => a -> a 
mcl x = 
let 
    mcl' x acc y 
    | compareWithDelta' x acc = acc 
    | otherwise = mcl' x (2*(x^(2*y+1)/(2*y+1))) (y+1) 
in 
    mcl' x 0 0 

但我有這些錯誤消息:

No instance for (Num a0) arising from a use of 'mcl' 
The type variable 'a0' is ambiguous 
Possible fix: add a type signature that fixes these type variable(s) 
Note: there are several potential instances: 
    instance Num Double — Defined in 'GHC.Float' 
    instance Num Float — Defined in 'GHC.Float' 
    instance Integral a => Num (GHC.Real.Ratio a) 
    — Defined in 'GHC.Real' 
    ...plus three others 
In the expression: mcl 1 
In an equation for 'it': it = mcl 1 

是什麼意思,以及如何要解決這個問題 ?

回答

5

簡短的回答是,你得到這個「不明確的類型變量」錯誤,因爲你的約束(Integral a, Floating a)是不一致的。沒有類型滿足這個要求,因此當默認嘗試找到1(在您的輸入表達式中)的類型時,它不能。

它從冪運算符(^)這些限制採取左側的整體參數(2.5^2是無效的,使用(^^)爲),並從與浮動1.0e-10比較。我猜想只想使用(^^)而不是(^)並刪除Integral約束。

如果您正在進行數值計算,最終肯定需要fromIntegralrealToFrac,這是不同數值類型之間的大錘轉換函數。只是爲你準備迎接未來。

還有一個指數運算符,(**),它在左側和右側都採用分數。 Haskell擁有三個不同的指數運算符的原因是,如果您好奇的話,還有其他問題。

+1

我希望GHC能夠爲這種情況指定用戶編程的警告/錯誤。如在「,如果在類型檢查/推理之後,你會發現'Num(a-> b)'表明......」。 – chi