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
?
Division of integers involves the grouping of items. It includes both positive numbers and negative numbers. Just like multiplication, the division of integers also involves the same cases. When you divide integers with two positive signs, Positive ÷ Positive = Positive → 16 ÷ 8 = 2.
When dividing an integer by an integer, the answer will be an integer (not rounded).
DIVISION. RULE 1: The quotient of a positive integer and a negative integer is negative. RULE 2: The quotient of two positive integers is positive. RULE 3: The quotient of two negative integers is positive.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With