Integral operators quot vs. div

后端 未结 2 1733
说谎
说谎 2020-11-29 02:04

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

相关标签:
2条回答
  • 2020-11-29 02:44

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

    0 讨论(0)
  • 2020-11-29 02:54

    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.

    0 讨论(0)
提交回复
热议问题