how come that following piece gives 4?
(\x -> (x-1) `mod` 5) 0
how come that following piece gives 4?
(\x -> (x-1) `mod` 5) 0
Because mod is defined as positive. div and mod operate on a floor basis, while / and rem do not.
Prelude> let x=(-2)
Prelude> let y=5
Prelude> (x`div`y)*y+(x`mod`y)
-2
Prelude> y*(truncate ((fromInteger x)/fromInteger y)) + (x`rem`y)
-2
Prelude> x`rem`y
-2
Prelude> x`mod`y
3
Prelude> (fromInteger x)/fromInteger y
-0.4
Prelude> x`div`y
-1
Addendum: As KennyTM rightly points out, I should have used quot, not /:
Prelude> (x`quot`y)*y+(x`rem`y)
-2
Prelude> (x`quot`y)
0
I simply did not remember it, and was too hasty to look it up. quot will do an integer division.
This the mathematical modulo operator, that is, a mod q
is the value r, 0 <= r < q, st.
a == i * q + r
This is different from the modulo operator from Java (%), where if a is negative, then a % q
is negative as well.