Haskell 中的舍入到最近的函数
Round-to-nearest function in Haskell
我需要一个四舍五入到最接近数字的函数,而不是四舍五入到偶数的默认函数。我写了一个,但问题是我是 Haskell 的新手,我认为它有一些语法错误。有人可以帮帮我吗?谢谢。
这是我到目前为止编写的代码:
rounding a
| (round a) - a > (-0.5) = round a
| otherwise = round a + 1
您正在混合类型,其中您从 round a
中减去 a
(一个类型取决于 rounding
参数的类型,而另一个始终是 Integral
) . round
需要 RealFrac
所以这是你应该从参数中得到的最少要求。与往常一样,我还建议将类型签名添加到 rounding
。下面显示了最简单的修复类型:
rounding a
| (fromIntegral (round a)) - a > (-0.5) = round a
| otherwise = round a + 1
为什么不
rounding a = floor (a + 0.5)
我需要一个四舍五入到最接近数字的函数,而不是四舍五入到偶数的默认函数。我写了一个,但问题是我是 Haskell 的新手,我认为它有一些语法错误。有人可以帮帮我吗?谢谢。 这是我到目前为止编写的代码:
rounding a
| (round a) - a > (-0.5) = round a
| otherwise = round a + 1
您正在混合类型,其中您从 round a
中减去 a
(一个类型取决于 rounding
参数的类型,而另一个始终是 Integral
) . round
需要 RealFrac
所以这是你应该从参数中得到的最少要求。与往常一样,我还建议将类型签名添加到 rounding
。下面显示了最简单的修复类型:
rounding a
| (fromIntegral (round a)) - a > (-0.5) = round a
| otherwise = round a + 1
为什么不
rounding a = floor (a + 0.5)