我试图学习Haskell,但我被卡在数字转换上,有人可以解释为什么Haskell编译器会对这段代码感到厌倦:
phimagic :: Int -> [Int]
phimagic x = x : (phimagic (round (x * 4.236068)))
Run Code Online (Sandbox Code Playgroud)
它会输出错误消息:
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))'
Run Code Online (Sandbox Code Playgroud)
我已经在方法签名上尝试了许多组合(添加了Integral,Fractional,Double等).有人告诉我,文字4.236068与问题有关,但无法弄明白.
Die*_*Epp 12
哈斯克尔不会自动转换你的东西,所以x * y只能当x和y具有相同的类型(你不能乘Int用Double,例如).
phimagic :: Int -> [Int]
phimagic x = x : phimagic (round (fromIntegral x * 4.236068))
Run Code Online (Sandbox Code Playgroud)
注意我们可以使用Prelude函数iterate更自然地表达phimagic:
phimagic = iterate $ round . (4.236068 *) . fromIntegral
Run Code Online (Sandbox Code Playgroud)