#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
or
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
http://cvs.haskell.org/cgi-bin/cvsweb.cgi/fptools/ghc/compiler/specialise/SpecConstr.lhs?rev=1.20&content-type=text/x-cvsweb-markup
Using "-O2 -ddump-simpl" with your (slightly corrected) example, one
can see that the Ints are indeed unboxed during recursion.
Cheers,
S.
More information about the Libraries
mailing list