简体   繁体   中英

How to tell that common subexpression elimination is happening or not in GHC?

Let's say I have a naively implemented function like this:

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + sqrt (b * b - 4 * a * c)) / (2 * a)
    ans2 = ((-b) - sqrt (b * b - 4 * a * c)) / (2 * a)

There are multiple identical subexpressions. How can I tell without reading core that common subexpression elimination is happening or not and to which parts of this?

Using trace might tell you as demonstrated in this SO question .

import Debug.Trace

quadratic a b c = (ans1, ans2)
  where
    ans1 = ((-b) + tr1 (sqrt (b * b - 4 * a * c))) / (2 * a)
    ans2 = ((-b) - tr2 (sqrt (b * b - 4 * a * c))) / (2 * a)
    tr1 = trace "ans1"
    tr2 = trace "ans2"

main = print $ quadratic 1 10 3

Compiling this with -O2 or -O3 shows both ans1 and ans2 in the trace output indicating that GHC did not perform the CSE. You get similar results if you use tr1 in both places.

The Haskell Wiki mentions that GHC only performs CSE in limited circumstances - (link) - and that you are advised to perform it yourself if you want to make sure it happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM