Reputation: 8277
In ghci I get the following:
λ> -1 `div` 2
0
However:
λ> map (`div` 2) [-1]
[-1]
The problem arose when I was using a function divPair
:
divPair :: (Int, Int) -> Int -> (Int, Int)
divPair (a, b) n = (a `div` n, b `div` n)
λ> divPair (-1, -2) 2
(-1,-1)
which was really a surprise to me as I expected it to produce (0, -1)
.
What happened here? I suppose I didn't really understand something about div
in Haskell.
Upvotes: 3
Views: 173
Reputation: 222368
That's because -1 `div` 2
is actually parsed as -(1 `div` 2)
which equals -0
or just 0
as 1 `div` 2
equals 0. You should use (-1) `div` 2
.
Prelude> -(1 `div` 2)
0
Prelude> (-1) `div` 2
-1
Upvotes: 10