152
votes

What exactly is the difference between mod and rem in Haskell?

Both seems to give the same results

*Main> mod 2 3
2
*Main> rem 2 3
2
*Main> mod 10 5
0
*Main> rem 10 5
0
*Main> mod 1 0
*** Exception: divide by zero
*Main> rem 1 0
*** Exception: divide by zero
*Main> mod 1 (-1)
0
*Main> rem 1 (-1)
0
4
Don't know Haskell, but it's likely these are the same operation. modulus == remainder. - Matthew Scharley
To be fair, it wasn't the same question. The other question assumed understanding of the answer to this question. - Dan Burton
@Dan Reading that question, because of another question I had (stackoverflow.com/questions/5892188/…), I realized the same :/ - Oscar Mederos
it's the same difference as between div and quot - newacct

4 Answers

199
votes

They're not the same when the second argument is negative:

2 `mod` (-3)  ==  -1
2 `rem` (-3)  ==  2
76
votes

Yes, those functions act differently. As defined in the official documentation:

quot is integer division truncated toward zero

rem is integer remainder, satisfying:

(x `quot` y)*y + (x `rem` y) == x

div is integer division truncated toward negative infinity

mod is integer modulus, satisfying:

(x `div` y)*y + (x `mod` y) == x

You can really notice the difference when you use a negative number as second parameter and the result is not zero:

5 `mod` 3 == 2
5 `rem` 3 == 2

5 `mod` (-3) == -1
5 `rem` (-3) == 2

(-5) `mod` 3 == 1
(-5) `rem` 3 == -2

(-5) `mod` (-3) == -2
(-5) `rem` (-3) == -2

 

20
votes

Practically speaking:

If you know both operands are positive, you should usually use quot, rem, or quotRem for efficiency.

If you don't know both operands are positive, you have to think about what you want the results to look like. You probably don't want quotRem, but you might not want divMod either. The (x `div` y)*y + (x `mod` y) == x law is a very good one, but rounding division toward negative infinity (Knuth style division) is often less useful and less efficient than ensuring that 0 <= x `mod` y < y (Euclidean division).

8
votes

In case you only want to test for divisibility, you should always use rem.

Essentially x `mod` y == 0 is equivalent to x `rem` y == 0, but rem is faster than mod.