Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does mod give a different result in an expression than in a function call?

Tags:

haskell

modulo

Say one wants to calculate the function:

f (x,y) = ((x `mod` 3)+(y `mod` 3)) `mod` 2

Then, if one expands f (-1,0) manually, one gets:

((-1 `mod` 3)+(0 `mod` 3)) `mod` 2
1

If one however uses an inline function, the result is:

let f (x,y) = ((x `mod` 3)+(y `mod` 3)) `mod` 2 in f (-1,0)
0

What happens when storing the function that yields not the expected result?

I assume this is because f uses Integral instead of Int?

like image 560
Willem Van Onsem Avatar asked Sep 17 '14 23:09

Willem Van Onsem


1 Answers

Looks like it's a matter of parsing. -1 `mod` 3 gets parsed as -(1 `mod` 3) and not (-1) `mod` 3.

*Main> -(1 `mod` 3)
-1
*Main> (-1) `mod` 3
2

Honestly, the way unary - works in Haskell is a bit of a hack that I personally find confusing. If I really need a negative literal, I usually just add the extra parentheses to be sure.

Another thing to consider is that Haskell has two modulo functions, mod and rem, that treat negative numbers differently. For more details, look to these two other questions.

like image 171
Tikhon Jelvis Avatar answered Oct 19 '22 20:10

Tikhon Jelvis