2013-10-10 43 views
3

我試着去學習哈斯克爾,但我被困在數轉換,能不能有人解釋爲什麼Haskell的編譯器在這個代碼要瘋了:舍入分數值INT

phimagic :: Int -> [Int] 
phimagic x = x : (phimagic (round (x * 4.236068))) 

它打印錯誤信息:

problem2.hs:25:33: 
    No instance for (RealFrac Int) arising from a use of `round' 
    Possible fix: add an instance declaration for (RealFrac Int) 
    In the first argument of `phimagic', namely 
     `(round (x * 4.236068))' 
    In the second argument of `(:)', namely 
     `(phimagic (round (x * 4.236068)))' 
    In the expression: x : (phimagic (round (x * 4.236068))) 


problem2.hs:25:44: 
    No instance for (Fractional Int) 
     arising from the literal `4.236068' 
    Possible fix: add an instance declaration for (Fractional Int) 
    In the second argument of `(*)', namely `4.236068' 
    In the first argument of `round', namely `(x * 4.236068)' 
    In the first argument of `phimagic', namely 
     `(round (x * 4.236068))' 

我已經嘗試了方法簽名(添加積分,分數,雙等等)的一些組合。有些東西告訴我,4.236068與問題有關,但無法解決問題。

回答

12

哈斯克爾不會自動轉換你的東西,所以x * y只有工作,如果xy具有相同的類型(你不能DoubleInt,例如)。

phimagic :: Int -> [Int] 
phimagic x = x : phimagic (round (fromIntegral x * 4.236068)) 

報告中,我們可以使用前奏功能iterate更自然地表達phimagic

phimagic = iterate $ round . (4.236068 *) . fromIntegral 
+0

喔的人...那麼明顯......如此美麗...... TKS –