2012-04-24 67 views
4

我遇到了一些問題,我新來的一個函數是fromIntegral函數。Haskell將Int轉換爲Floating

基本上我需要採取兩個int參數和返回數字的百分比,但是當我運行我的代碼,它不斷給我這個錯誤:

代碼:

percent :: Int -> Int -> Float 
percent x y = 100 * (a `div` b) 
where a = fromIntegral x :: Float 
     b = fromIntegral y :: Float 

錯誤:

No instance for (Integral Float) 
arising from a use of `div' 
Possible fix: add an instance declaration for (Integral Float) 
In the second argument of `(*)', namely `(a `div` b)' 
In the expression: 100 * (a `div` b) 
In an equation for `percent': 
    percent x y 
     = 100 * (a `div` b) 
     where 
      a = fromIntegral x :: Float 
      b = fromIntegral y :: Float 

我讀了'98 Haskell前奏,它說有這樣一個函數叫fromInt,但它從來沒有工作,所以我不得不這樣做,但它仍然無法正常工作。幫幫我!

+1

我懷疑98報告稱有一個fromInt。 – augustss 2012-04-24 18:04:33

回答

13

看的div類型:

div :: Integral a => a -> a -> a 

您可以輸入不進行改造,以Float然後用div

使用(/)代替:

(/) :: Fractional a => a -> a -> a 

下面的代碼工作:

percent :: Int -> Int -> Float 
percent x y = 100 * (a/b) 
    where a = fromIntegral x :: Float 
     b = fromIntegral y :: Float 
+0

呵呵,爲大家歡呼,我一直在使用'div',忘了看看替代方案!我的壞,再次感謝! – 2012-04-24 22:48:45

+1

爲簡潔起見,您不需要強制使用類型':: Float' – rotskoff 2012-04-25 01:45:26

+0

使用'Data.Function.on',您可以在'fromIntegral)xy'上寫'percent xy = 100 *((/)'(將'通過反引號) – Landei 2012-04-25 09:31:50