#ifdef considered harmful (was: DData)

Simon Marlow simonmar at microsoft.com
Fri Apr 16 11:28:54 EDT 2004

> Hmm, wouldn't it be nice to have a "FastInt" library which re-bound 
> the appropriate types and functions?  Haskell libraries are 
> chock-a-block with instances of "#ifdef __GHC__" which define things 
> in terms of Int# instead of Int.  We could simplify all those 
> libraries if we did it just once, in one place.
> The problem, of course, is that the naive non-GHC user could write a 
> library which used "FastInt" polymorphically, and write code that 
> wasn't portable to GHC.  I don't think there's an easy, magic 
> solution 
> there.  Perhaps such a library would be named 
> FastIntWhichIPromiseToTestWithGHC.

Most of the time it's unnecessary to use an explicit Int#.  If your Int
is in a data structure, you can use 

  {-# UNPACK #-} !Int

which is portable, and compiles to an unboxed Int in GHC >= 6.2.

However, depending on how you use the Int, GHC might need to insert
reboxing code; e.g. if you store the Int in a list.  The only reason to
use an explicit Int# would be if you really wanted to be sure that no
boxing was ever happening.

The above trick is used in several places in the libraries currently:
GHC's IO libraries and Data.HashTable are two good examples.


More information about the Libraries mailing list