如何在Haskell中从Float转换为Int

Saj*_*wer 6 haskell type-conversion

我在Haskell中编写了一个函数

toInt :: Float -> Int
toInt x = round $fromIntegral x
Run Code Online (Sandbox Code Playgroud)

它应该接受一个Float并返回等效的Int.我来自C编程背景,在C中,我们可以把它当作(int)x.

但是,在这种情况下,我得到以下编译错误

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
Run Code Online (Sandbox Code Playgroud)

有关如何解决此问题的任何想法?

Cha*_*ert 9

您的类型注释指定x应该是a Float,这意味着它不能是参数,fromIntegral因为该函数采用积分.

你可以改为传递xround:

toInt :: Float -> Int
toInt x = round x
Run Code Online (Sandbox Code Playgroud)

反过来可以减少到:

toInt :: Float -> Int
toInt = round
Run Code Online (Sandbox Code Playgroud)

这意味着round除了你有一些特殊的舍入方式之外,你可能会更好地开始使用.

  • 那行得通,谢谢。有人告诉我 Haskell 的解决方案后我觉得很傻哈哈 (2认同)