fromInteger :: Integer -> Int/Word

Simon Marlow simonmar@microsoft.com
Fri, 11 Apr 2003 11:29:25 +0100


=20
> Ross Paterson <ross@soi.city.ac.uk> writes:
> > Under Hugs, fromInteger (and thus fromIntegral) throws an exception
> > if the argument is outside the representable range of values, while
> > GHC just truncates. =20
>=20
> I would say that GHC implements a performance optimization by dropping
> the check and that the behaviour outside the range of Int should be
> treated as undefined (which is not the same as 'implementation
> defined').

If I remember correctly (this point has come up several times in the
past), the reasoning is something like this: since Int arithmetic
doesn't do any overflow checking, it's inconsistent for fromInteger to
do any.

Q: should  (0xffffffff :: Int32) =3D=3D (-1 :: Int32)

we take the view that it's useful if this holds.  So fromInteger on
*sized* integral types doesn't do any overflow checking.

Now, if  a, b :: Int,  should

   (a + b) :: Int =3D=3D fromInteger (toInteger a + toInteger b) :: Int

(eg. take a to be maxBound :: Int, and b to be 1, and this doesn't hold
in Hugs).

We take the view that this should hold, i.e. it makes no difference if
the addition is done with Int or Integer because the final result is
modulo 2^n (where n is the number of bits in Int).  If you were to do
overflow checking on Int addition, then it would also make sense to do
overflow checking on fromInteger, and the above property would still
hold, but to do one but not the other is inconsistent.

Cheers,
	Simon