将小数值舍入为Int

时间:2013-10-10 05:34:43

标签: haskell

我试图学习Haskell,但是我被卡在数字转换上,有人可以解释为什么Haskell编译器会对这段代码感到生气:

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))'

我已经在方法签名上尝试了许多组合(添加了Integral,Fractional,Double等)。有些东西告诉我,文字4.236068与问题有关,但无法弄明白。

1 个答案:

答案 0 :(得分:12)

Haskell不会自动为您投放内容,因此x * y仅在xy具有相同类型时才有效(您无法将Int乘以{{ 1}},例如)。

Double

注意我们可以使用Prelude函数phimagic :: Int -> [Int] phimagic x = x : phimagic (round (fromIntegral x * 4.236068)) 更自然地表达iterate

phimagic