GHC is bad at CSE. Of course, in general CSE might not be a good idea,
but with strict computations it is. So someone needs to add a CSE pass.<br><br><div class="gmail_quote">On Sat, Mar 29, 2008 at 2:23 AM, Don Stewart <<a href="mailto:dons@galois.com">dons@galois.com</a>> wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">conal:<br>
<div><div></div><div class="Wj3C7c">> I'd like to know if it's possible to get GHC to perform some simple CSE<br>
> for function-level programming. Here's a simple example:<br>
><br>
> liftA2 (*) sin sin :: Double -> Double<br>
><br>
> which inlines and simplifies to<br>
><br>
> \ t -> sin t * sin t<br>
><br>
> A more realistic, equivalent, example:<br>
><br>
> let b = sin <$> id in liftA2 (*) b b<br>
><br>
> Can GHC be nudged into computing 'sin t' once rather than twice?<br>
><br>
<br>
</div></div>So GHC does do some light CSE, but not in this case, as far as I could<br>
see.<br>
<br>
I had a go with a rewrite rule that I felt should have matched, but it<br>
didn't seem to want to fire. Possibly the dictionaries were getting in<br>
the way.<br>
<br>
<br>
import System.Environment<br>
import Prelude hiding (sin)<br>
import qualified Prelude<br>
<br>
sin :: Double -> Double<br>
sin x = Prelude.sin x<br>
{-# NOINLINE sin #-}<br>
<br>
times :: Double -> Double -> Double<br>
times x y = x * y<br>
{-# NOINLINE times #-}<br>
<br>
{-# RULES<br>
<br>
"sin/cse" forall x.<br>
times (sin x) (sin x) = case Prelude.sin x of y -> y * y<br>
<br>
#-}<br>
<br>
<br>
main = do<br>
[x] <- getArgs<br>
let n = read x<br>
print $ sin n `times` sin n<br>
<br>
<br>
_______________________________________________<br>
Glasgow-haskell-users mailing list<br>
<a href="mailto:Glasgow-haskell-users@haskell.org">Glasgow-haskell-users@haskell.org</a><br>
<a href="http://www.haskell.org/mailman/listinfo/glasgow-haskell-users" target="_blank">http://www.haskell.org/mailman/listinfo/glasgow-haskell-users</a><br>
</blockquote></div><br>