2016-11-28 88 views
2

我試圖定義:轉換浮動到整數

square :: Integer -> Integer 
square = round . (** 2) 

和我得到:

<interactive>:9:9: error: 
    • No instance for (RealFrac Integer) arising from a use of ‘round’ 
    • In the first argument of ‘(.)’, namely ‘round’ 
     In the expression: round . (** 2) 
     In an equation for ‘square’: square = round . (** 2) 

<interactive>:9:18: error: 
    • No instance for (Floating Integer) 
     arising from an operator section 
    • In the second argument of ‘(.)’, namely ‘(** 2)’ 
     In the expression: round . (** 2) 
     In an equation for ‘square’: square = round . (** 2) 

我還在這個語言新,我似乎是不能轉換的實例浮動到整數。有誰知道我該怎麼做?

回答

5

這是一個附錄亞歷克的回答,這是正確的,幫助你理解的錯誤消息。該類型的(**)

(**) :: (Floating a) => a -> a -> a 

所以

(** 2) :: (Floating a) => a -> a 

(因爲字面2可以是我們所需要的任何數字型)。但是aInteger,因爲你的函數聲明爲Integer作爲輸入。所以,現在

(** 2) :: Integer -> Integer --provided that there is a `Floating Integer` instance 

這說明你的第二個錯誤,因爲沒有FloatingInteger實例 - Integer■不要支持浮點操作,如sin(與任意實數冪)。

然後你通過這個功能,這是一個Integer的輸出,一起round其類型

round :: (RealFrac a, Integral b) => a -> b 

我們知道輸入,a,是Integer,因爲它是從(** 2)作爲我們討論的到來,和輸出b也是Integer,因爲您的函數的輸出被聲明爲Integer。所以,現在你有

round :: Integer -> Integer 
    --provided there are `Integral Integer` and `RealFrac Integer` instaces 

有一個IntegralInteger實例,以便使用,但沒有RealFracInteger實例,並解釋你的第一個錯誤。 Integer s不支持像提取分子一樣的類似理性的操作(儘管我想他們可以......)。

1

的附錄中@ luqui的答案,如果你想修正這個錯誤(而不是僅僅關注@亞歷克的優秀的解決方案),你可以在Integer參數轉換到一個Floating實例:

square :: Integer -> Integer 
square = round . (** 2) . fromInteger 
+0

這是盧基的答案是否可以用於評論亞歷克的答案,這是值得商榷的,但這肯定可能是對盧奎答案的評論。 – chepner