如何在Haskell中将Float转换为Int

16

我用Haskell编写了一个函数

toInt :: Float -> Int
toInt x = round $fromIntegral x

这个函数应该接受一个浮点数并返回相应的整数。我来自C编程背景,在C中,我们可以将它强制转换为int。

然而,在这种情况下,我会得到以下编译错误

No instance for (Integral Float)
arising from a use of `fromIntegral'
In the second argument of `($)', namely `fromIntegral x'
In the expression: round $ fromIntegral x
In an equation for `toInt': toInt x = round $ fromIntegral x

有没有任何解决这个问题的想法?


也许你可以尝试这个 round 3.2 :: Int - Aleph0
3
如果你需要查找一个类型已知的函数,比如Float -> Int,那么你可以在Hayoo或Hoogle上搜索该类型的函数。 - Redu
1个回答

22

你的类型注释指定了x应该是一个Float,这意味着它不能成为fromIntegral的参数,因为该函数需要一个整数。

相反,你可以将x直接传递给round

toInt :: Float -> Int
toInt x = round x

这反过来可以被简化为:

toInt :: Float -> Int
toInt = round

这意味着你最好一开始就使用round,除非你有一些特殊的舍入方式。


2
好的,谢谢。有人用Haskell告诉我解决方案后,我感觉自己很傻哈哈。 - Sajid Anower

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接