1

how come that following piece gives 4?

(\x -> (x-1) `mod` 5) 0
Gennadi
  • 41
  • 6

2 Answers2

6

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
  • 15,414
  • 2
  • 28
  • 26
5

-1 modulo 5 is, by definition, 4.

IVlad
  • 43,099
  • 13
  • 111
  • 179