Type class Integral has two operations quot
and div
, yet in the Haskell 2010 Language Report it is not specified what they're supposed to do. Assuming that div
is integral division, what does quot
differently, or what is the purpose of quot
? When do you use one, and when the other?
-
1This seems like a promising link: cdsmith.wordpress.com/2007/06/02/…– Stuart GolodetzNov 13, 2011 at 11:19
2 Answers
To quote section 6.4.2 from the Haskell report:
The quot
, rem
, div
, and mod
class methods satisfy these laws if y is non-zero:
(x `quot` y)*y + (x `rem` y) == x
(x `div` y)*y + (x `mod` y) == x
quot
is integer division truncated toward zero, while the result of div
is truncated toward negative infinity.
The div
function is often the more natural one to use, whereas the quot
function corresponds to the machine instruction on modern machines, so it's somewhat more efficient.
-
6+1 for the discussion of when you might prefer one over the other Nov 13, 2011 at 11:35
-
24or, equivalently, the result of
mod
has the same sign as the divisor, while the result ofrem
has the same sign as the dividend– newacctNov 13, 2011 at 12:12 -
Thanks for the answer, especially for mentioning the paragraph in the HR. I was looking only in chapter 9.– IngoNov 13, 2011 at 16:05
-
I worked this out as an English sentence to help me grok it. I believe this describes the truth for both equations; the variation in meaning is determined by what is meant by "quotient" (i.e. whether using quot or div semantics). Here goes: "The remainder is the difference between the dividend and the product of the quotient and the divisor." Mar 31, 2016 at 23:58
The two behave differently when dealing with negative numbers. Consider:
Hugs> (-20) `divMod` 3
(-7,1)
Hugs> (-20) `quotRem` 3
(-6,-2)
Here, -7 * 3 + 1 = -20
and -6 * 3 + (-2) = -20
, but the two ways give you different answers.
Also, see here: http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html
The definition for quot
is "integer division truncated toward zero", whereas the definition for div
is "integer division truncated toward negative infinity".