I found a quite strange inconsistency between the behaviour of div and /.
*ghci> :t 1 `div` 0
1 `div` 0 :: Integral a => a
*ghci> :t 1 / 0
1 / 0 :: Fractional a => a
*ghci> 1 / 0
Infinity
*ghci> 1 `div` 0
*** Exception: divide by zero
I was quite surprised to notice that the fractional division by zero leads to Infinity, whereas div correctly leads to an exception.
A NaN could be acceptable too for /, but why Infinity? There is no mathematical justification for such a result. Do you know the reason for this, please?
The reason that
divdoes not returnInfinityis simple–there is no representation for infinity in theIntegertype./returnsInfinitybecause it follows the IEEE 754 standard (which describes floating point number representations) since the defaultFractionaltype isDouble. Other languages with floating point numbers (e.g. JavaScript) also exhibit this behavior.To make mathematicians cringe even more, you get a different result if you divide by negative 0, despite the fact that
-0 == 0for floats:This is also behavior from the standard.
If you use a different fractional type like
Rational, you will get the behavior you expect:Coincidentally, if you’re wondering about why
IntegerandDoubleare the types in question when your actual operation does not reference them, take a look at how Haskell handles defaulting types (especially numeric types) in the report.The short version is that if you have an ambiguous type from the
Numclass, Haskell will first tryIntegerand thenDoublefor that type. You can change this with adefault (Type1, Type2...)statement or turn it off with adefault ()statement at the module level.