Integral operators quot vs. div

后端 未结 2 1750
说谎
说谎 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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".

提交回复
热议问题