This is an example from Learn you a Haskell:
ghci> [ x*y | x <- [2,5,10], y <- [8,10,11], x*y > 50]
[55,80,100,110]
So, what's going on here, will x*y
be calculated twice or once?
It would be calculated twice unless common subexpression elimination occurs.
Depending on inlining and your optimization level, GHC may do quite aggressive things with the list comprehension.
In general, you should explicitly share common expressions to guarantee sharing.
To be sure of the compiler's behaviour, prefer:
[ product | x <- [2, 5, 10]
, y <- [8, 10, 11]
, let product = x * y
, product > 50]
Looking into the core when compiled with -O2 option it has following lines (relevant and simplified)
case (y_aAD * sc_s1Rq) > 50 of
False -> go_XB2 sc1_s1Rr;
True -> (y_aAD * sc_s1Rq):(go_XB2 sc1_s1Rr)
This clearly shows that the multiplication is calculated twice, so it is better use common expression to prevent recomputation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With