Behavior of fromInteger on out-of-range arguments

Jan-Willem Maessen
Tue, 26 Feb 2002 10:19:09 -0500

I've recently run up against the following rather annoying
inconsistency between haskell implementations:

Nat> fromInteger 4294967264 :: Int

Program error: {primIntegerToInt 4294967264}

Nat> fromInteger 4294967264 :: Int

I don't have nhc installed at the moment, so I can't tell you offhand
which side of the debate it falls on.

There are interesting arguments for both views, depending on whether
you think of Int as being "Signed integers modulo 2^k" or "fast but
impoverished integers".

The difference only becomes a real problem when we add Int and Word:
multiple sizes of signed and unsigned ints.  How do we convert between
them?  In particular, how do we do a simple bitwise conversion
between, say, Int32 and Word32?  GHC takes the position that
"fromIntegral is the only tool you will ever need".  Hugs provides a
special conversion routine for every pair of types.  

I'm trying to write code which works in both systems (and hopefully
can be used in nhc as well).  As a result, I'd love to see a
consistent story here.  

It'd be lovely if the Haskell report took a stand on the issue, but I
suspect that may be too much to hope for.  Absent a cue in the report,
it seems the FFI specification of the Int and Word should specify how
to interconvert between the various types.

I'm actually rather fond of the "integers modulo 2^k" view of Int and
its ken.  I think it does a grave disservice to beginning programmers
to tell them that Int is simply a fast, impoverished Integer; I expect
expert programmers to understand range limits and overflow.  It also
means that there are a few nice algebraic identites involving

  (fromInteger (a + b) :: Int) == (fromInteger a + fromInteger b :: Int)
  (fromInteger (a - b) :: Int) == (fromInteger a - fromInteger b :: Int)

Frankly, though, I see compelling aesthetic arguments for either
behavior.  I'd rather implementations agreed on the behavior of
fromInteger, than see my "favorite" behavior supported.

-Jan-Willem Maessen

PS - I should note that I don't use the FFI, nor do I have any
immediate intention of doing so.  I'm using Word types because
comparison of Words interacts nicely with bitwise operations.