2016-04-01 88 views
0

我只是寫在Haskell一個簡單的代碼,曖昧例如在Haskell

coo x y = ((lim-1)*y*(y-1)`div`2) + (y*(y-1)*(sum (map (\j->(x`div`j)-j) [2..lim]))) 
    where 
    lim = floor (sqrt x) 

但是當我使用了ghci首席運營官10 10「,它給了我下面的錯誤:

<interactive>:3:1: 
No instance for (Floating a0) arising from a use of ‘it’ 
The type variable ‘a0’ is ambiguous 
Note: there are several potential instances: 
    instance Floating Double -- Defined in ‘GHC.Float’ 
    instance Floating Float -- Defined in ‘GHC.Float’ 
In the first argument of ‘print’, namely ‘it’ 
In a stmt of an interactive GHCi command: print it 

什麼發生了什麼?我確信我匹配所有類型都是正確的。

+0

你將需要(或內)'COO 10 10'本身就是一個明確的類型簽名。要明白爲什麼,在GHCi中輸入':t coo'。類型是正確的,但'coo 10 10'仍然是多態的。你必須指定你想要'coo 10 10 :: Float'還是'coo 10 10 :: Double'。 –

+0

@Rhymoid nope ...雖然錯誤會指出這不是問題 - 嘗試一下:你會得到另一個錯誤(告訴你'Float'或'Double'不是'Integral') – Carsten

+0

'sqrt ::浮動a => a - > a';你可以使用'sqrt(fromIntegral x)',但要小心精度損失。 – Ryan

回答

4

如果你仔細觀察(或詢問GHCI),你會看到你的函數的類型

coo :: (Floating a, Integral a, RealFrac a) => a -> a -> a 

告訴GHC使用某種類型的a這既是FloatingIntegral,這將讓困難(有在前奏沒有這樣的類型)


我不是100%肯定你正在嘗試做的,但要解決這個問題一個辦法是改變lim到:

lim = floor (sqrt $ fromIntegral x) 

這將產生

λ> coo 10 10 
360 
+0

你能建議如何解決這個問題嗎? – CYC

+1

完成 - 但我不知道你的函數應該做什麼 – Carsten

+0

正確的方法是實現[整數平方根](https://en.m.wikipedia.org/wiki/Integer_square_root)函數。 –