tags:

views:

154

answers:

3

how come that following piece gives 4?

(\x -> (x-1) `mod` 5) 0
+5  A: 

-1 modulo 5 is, by definition, 4.

IVlad
you right, yes, thanks
Gennadi
it differs by programming language, and by which mod function you use
newacct
+6  A: 

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.

Yann Vernier
The correspondence of `div` should be `quot`, not `/`.
KennyTM
A: 

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.

HaskellElephant