Search code examples
haskell

Constant function optimization


If I have a function fun like:

-- For example, `SomeRecord` can have more than 2 fields,
-- but 20 or 30
data SomeRecord a b = SomeRecord {
  f1 :: a -> b,
  f2 :: a -> b -> Bool
}

fun :: SomeRecord Int Bool
fun = SomeRecord ...

and then I call fun in different places in my program, will the code produced by GHC call fun every time or it will be replaced by some "reference" to this nullary (actually constant) function's result like C compilers do it with constants? Something like "call it for the first time then replace with this value everywhere in any nesting depth" (or GHC could do it without call even), is it possible? Do I need some special compiler flags for it (I use just -O2 currently)?


Solution

  • In GHC, fun will compile to an object that, when evaluated for the first time, overwrites itself with the evaluated value. This will happen even with no optimizations turned on at all. (Indeed, turning that behavior off is the hard task, not enabling it.)