how come that following piece gives 4?
(\x -> (x-1) `mo开发者_JS百科d` 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.
-1 modulo 5 is, by definition, 4.
精彩评论