- x `div` y = if x > 0 && y < 0 then quotInt (x-y-1) y
- else if x < 0 && y > 0 then quotInt (x-y+1) y
- else quotInt x y
+ n `div` d
+ | n > 0 && d < 0 = mk_neg (quotInt (n-d-1) d)
+ | n < 0 && d > 0 = mk_neg (quotInt (n-d+1) d)
+ | otherwise = quotInt n d
+ where
+ {-
+ - the result of (integral) division is
+ defined as being truncated towards
+ negative infinity. (see Sec 6.3.2 of
+ the Haskell 1.4 report.)
+
+ - in the case of Int, if either nominator or
+ denominator is negative, we adjust the nominator
+ to account for the above property before
+ computing the quotient.
+
+ - in the case of Int, the adjustment of the
+ nominator runs the risk of overflowing. If
+ we make the assumption that arithmetic is
+ modulo word size, and adjust the final result
+ to account for this.
+ -}
+
+ mk_neg r
+ | r <= 0 = r
+ | otherwise = -(r+1)
+