问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/25901994/why-does-mod-give-a-different-result-in-an-expression-than-in-a-function-call