#ifdef considered harmful (was: DData)

Jan-Willem Maessen - Sun Labs East Janwillem.Maessen at Sun.COM
Mon Apr 19 11:05:48 EDT 2004


Jan-Willem Maessen - Sun Labs East wrote:
Simon Marlow wrote:
>> 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.


The real problem, of course, isn't the data structures at all---GHC does
an excellent job with these (though the "UNPACK" pragma is a
revelation).  The actual problem is function arguments.  GHC can't do
worker-wrapper unless a function is strict.  Often we end up with
something like this:

data Tree a = Branch !Int a (Tree a) (Tree a)

lookfor :: Int -> Tree a -> Maybe a
lookfor Leaf key = Nothing
lookfor (Branch k v l r) key
   | key==k    = Just v
   | key < k   = lookfor l key
   | otherwise = lookfor r key

Here we don't use "key" in the first clause, so GHC isn't allowed to
unbox.  Most of the uses of Int# that I've seen in library code have
been workarounds to this problem.  In this case, being able to write

lookfor :: FastInt -> Tree a -> Maybe a

might give us some hope of getting the compiler to generate the unboxed
code we might want, yet still afford us the opportunity to use boxed
types if that's not possible.

We could do this today without changing the language or the compilers.
The library would have to be carefully coded...

-Jan-Willem Maessen



More information about the Libraries mailing list