Why does the mode give a different result in the expression than when calling a function?

Let's say you need to compute a function:

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

Then, if f (-1,0) manually expanded once, it turns out:

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

If, however, a built-in function is used, the result:

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

What happens when you save a function that does not produce the expected result?

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

+5
source share
1 answer

This seems to be a parsing issue. -1 `mod` 3 parsed as -(1 `mod` 3) , not (-1) `mod` 3 .

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

Honestly, the unary way - 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 extra parentheses.

Another thing to keep in mind is that Haskell has two modular functions, mod and rem , that handle negative numbers differently. See these other two questions for more information.

+9
source

Source: https://habr.com/ru/post/1202820/


All Articles