#ifdef considered harmful (was: DData)

Sven Panne Sven.Panne at aedion.de
Mon Apr 19 18:33:45 EDT 2004

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

If that's the only concern, there is no real problem. One can do:

a) Help GHC a bit by hand with something like

       lookfor Leaf key | key == key = Nothing


       lookfor Leaf key = key `seq` Nothing

    Not very nice, but a "traditional" way of improving strictness.

b) Use GHC's -O2 flag, enabling specialization over constructors, which
    is exactly what you're looking for, see the "Game Plan" comment at
    the beginning of


    Using "-O2 -ddump-simpl" with your (slightly corrected) example, one
    can see that the Ints are indeed unboxed during recursion.


More information about the Libraries mailing list