Why is + overloaded but / not?

Submitted by metaperl on Sun, 04/23/2006 - 11:09am.

*Main> 5/2
*Main> 5 `div` 2
*Main> 5.0 + 2.0
*Main> 5 + 2

Submitted by Cale Gibbard on Tue, 04/25/2006 - 1:07am.
Prelude> :type (/)
(/) :: (Fractional a) => a -> a -> a

Division is overloaded -- you can use it with Float, Double, Complex Double, Rational, etc., just not Int or Integer.

The issue is just that div and (/) are fundamentally different operations with different rules, so they were separated in the design of the Prelude. It ought to be true that (at least to a reasonable approximation), that 1/(1/a) = a, for nonzero a, or perhaps more importantly that a * (1/a) = 1, but if (/) is integer division, the first results in division by 0, and the second results in 0 instead of 1. These rules don't *quite* hold for floating-point types, but all operations on them come with margins of error anyway -- they do a decent job of trying to approximate division in the Real numbers, where those properties are satisfied exactly. However, with integers, there just is no operation (/) which satisfies a * (1/a) = 1 for all nonzero integers a. (Regardless of what integer (1/a) is, a * (1/a) will be divisible by a, so choose a = 2, and the result will have to be divisible by 2, which 1 isn't.)

However, despite not being a field, integers form a so-called Euclidean domain -- a system of numbers where 'division with remainder' is a meaningful concept. We use div to mean this weaker sense of division. It is a bit of a shame though that due to the way that the classes are laid out, it's unreasonable to define div for things like Float, Rational, etc, (you'd want to define it to be the same as (/)), but this isn't usually such a big deal in practice.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.