为什么不可能在Haskell中划分整数? [英] Why it is impossible to divide Integer number in Haskell?
问题描述
这段代码
(4 :: Integer)/ 2
会导致错误:
(4 :: Integer)/ 2
在'it'的等式中:it =(4 :: Integer)/ 2
为什么?
我需要指定 p>
fromIntegral(4 :: Integer)/ 2
即可获得结果。但是如果我需要一个实数而不是 2.0
?因为 Integer
类型没有 ,所以 小数
实例。
(/)
的类型为小数a => a - > a - >一个
。考虑当 a = Integer
时会发生什么。你有整数 - >整数 - >整数
。但 1/2
是不是整数,它是 0.5
。因此,适合除法运算符的唯一方法是对结果进行轮换。但是不是单独的一种方法,最好的选择取决于应用程序,因此决定不提供该实例。 如果您想执行整数除法,请使用 div
或 quot
函数(它们使用不同的舍入)。
否则转换为支持像 Rational 这样定义明确的除法操作的东西(这就是<整数$ c>来自整数
正在做)。
This code
(4 :: Integer) / 2
will lead to error:
No instance for (Fractional Integer) arising from a use of ‘/’
In the expression: (4 :: Integer) / 2
In an equation for ‘it’: it = (4 :: Integer) / 2
Why?
I need to specify
fromIntegral(4 :: Integer) / 2
to get a result. But what if I need a real number and not 2.0
?
Because the Integer
type has no Fractional
instance.
The type for (/)
is Fractional a => a -> a -> a
. Consider what happens when a = Integer
. You'd have Integer -> Integer -> Integer
. But 1/2
is not an integer, it's 0.5
. So the only way to fit the division operator would be to round the result. But there is not a single way to round, and the best choice depends on the application, hence it was decided to not provide that instance.
If you want to perform integer division use the div
or quot
functions (they use different rounding).
Otherwise convert to something that supports a well-defined division operation like Rational
(this is what the fromIntegral
is doing).
这篇关于为什么不可能在Haskell中划分整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!