为什么mod在表达式中给出的结果与函数调用中给出的结果不同? [英] Why does mod give a different result in an expression than in a function call?
问题描述
假设要计算该函数:
f (x,y) = ((x `mod` 3)+(y `mod` 3)) `mod` 2
然后,如果有人手动展开f (-1,0)
,就会得到:
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?
我认为这是因为f
使用Integral
而不是Int
吗?
I assume this is because f
uses Integral
instead of Int
?
推荐答案
好像是解析问题. -1 `mod` 3
被解析为-(1 `mod` 3)
而不是(-1) `mod` 3
.
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
老实说,一元-
在Haskell中的工作方式有点像个hack,我个人觉得很困惑.如果我真的需要一个否定的文字,我通常只需添加额外的括号即可.
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.
要考虑的另一件事是,Haskell具有两个模函数,分别是mod
和rem
,它们对负数的处理方式有所不同.有关更多详细信息,请参见这些
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.
这篇关于为什么mod在表达式中给出的结果与函数调用中给出的结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!