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

时光总嘲笑我的痴心妄想 提交于 2019-12-10 14:26:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!