gpt4 book ai didi

haskell - 将小数值舍入为 Int

转载 作者:行者123 更新时间:2023-12-03 06:19:30 24 4
gpt4 key购买 nike

我正在尝试学习 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))'

我已经在方法签名上尝试了多种组合(添加积分、分数、 double 等)。有些东西告诉我,文字 4.236068 与问题有关,但无法弄清楚。

最佳答案

Haskell 不会自动为您转换内容,因此 x * y 仅当 xy 具有相同类型时才有效(您可以例如,不要将 Int 乘以 Double)。

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

请注意,我们可以使用 Prelude 函数 iterate 更自然地表达 phimagic:

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

关于haskell - 将小数值舍入为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19287818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com