When is the difference between quotRem and divMod useful?

前端 未结 3 1280
猫巷女王i
猫巷女王i 2020-12-02 12:19

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`          


        
3条回答
  •  失恋的感觉
    2020-12-02 13:05

    Many languages have a "mod" or "%" operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say:

    (-11)/5 = -2
    (-11)%5 = -1
    5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.
    

    Haskell's quot and rem are intended to imitate this behaviour. I can imagine compatibility with the output of some C program might be desirable in some contrived situation.

    Haskell's div and mod, and subsequently Python's / and %, follow the convention of mathematicians (at least number-theorists) in always truncating down division (not towards 0 -- towards negative infinity) so that the remainder is always nonnegative. Thus in Python,

    (-11)/5 = -3
    (-11)%5 = 4
    5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.
    

    Haskell's div and mod follow this behaviour.

提交回复
热议问题