Integral operators quot vs. div

Haskell

Haskell Problem Overview


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?

Haskell Solutions


Solution 1 - Haskell

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.

Solution 2 - Haskell

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".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIngoView Question on Stackoverflow
Solution 1 - HaskellaugustssView Answer on Stackoverflow
Solution 2 - HaskellStuart GolodetzView Answer on Stackoverflow