Integral Operators quot vs. div

The Integral class type has two quot and div operations, but the Haskell 2010 language report does not indicate what they should do. Assuming the div is an integral division, what does quot mean differently or what is the purpose of quot ? When do you use one and the other?

+43
haskell
Nov 13 '11 at 11:08
source share
2 answers

To quote section 6.4.2 from a Haskell report:

Class methods quot, rem, div, and mod satisfy these laws if y is nonzero:

 (x 'quot' y)⋆y + (x 'rem' y) == x (x 'div' y)⋆y + (x 'mod' y) == x 

quot is an integer division truncated to zero, and the result of a div is truncated to negative infinity.

The div function is often more natural to use, while the quot function corresponds to the machine instruction on modern machines, so it is somewhat more efficient.

+82
Nov 13 '11 at 11:27
source share

Both act 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 methods 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 to zero," while the definition for div is "integer division truncated to negative infinity."

+24
Nov 13 '11 at 11:23
source share



All Articles