Haskell 将分数值舍入为Int
我试图学习Haskell,但我在数字转换方面遇到了困难,有人能解释一下为什么Haskell编译器会对这段代码发火:Haskell 将分数值舍入为Int,haskell,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:
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与问题有关,但无法解决问题。Haskell不会自动为您转换内容,因此
x*y
仅在x
和y
具有相同类型(例如,您不能将Int
乘以Double
)时才有效
注意:我们可以使用Prelude函数iterate
更自然地表达phimagic
:
phimagic = iterate $ round . (4.236068 *) . fromIntegral
phimagic = iterate $ round . (4.236068 *) . fromIntegral