[Haskell-cafe] GHC magic optimization ?

Neil Brown nccb2 at kent.ac.uk
Fri Dec 4 05:36:09 EST 2009

Emmanuel CHANTREAU wrote:
> I will take an example:
> f x y= x+y
> The program ask the user to enter two numbers and print the sum. If the
> user enter "1 2" "f 1 2=3" is stored and a gargage collector is used to
> remove this dandling expression later ?
> If the user enter again "1 2", ghc search in dandling results to
> try to find the result without computing it again ?

I think what you're asking is how Haskell knows at run-time for which 
expressions it can re-use the results.  The answer is: it doesn't, it 
works it out at compile-time.  So if you have:

f x y = x + y

And at some point in your program you call f 1 2, and later on from a 
totally separate function you call f 1 2, the function will be evaluated 
twice (assuming 1 and 2 weren't known constants at compile-time).  But 
let's say you have:

g x y = f x y * f x y

Now the compiler (i.e. at compile-time) can do some magic.  It can spot 
the common expression and know the result of f x y must be the same both 
times, so it can convert to:

g x y = let z = f x y in z * z

Now, the Haskell run-time will evaluate f x y once, store the result in 
z, and use it twice.  That's how it can use commonalities in your code 
and avoid multiple evaluations of the same function call, which I 
*think* was your question.



More information about the Haskell-Cafe mailing list