Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active July 29, 2019 16:46
Show Gist options
  • Save carymrobbins/9bcf9d7d023f8dc21c7c9d3dcdbcbb9a to your computer and use it in GitHub Desktop.
Save carymrobbins/9bcf9d7d023f8dc21c7c9d3dcdbcbb9a to your computer and use it in GitHub Desktop.
What happens when you use NOINLINE on a function defined in a where clause? Hint: optimization levels matter!
import System.IO.Unsafe
main :: IO ()
main = do
thing 1
thing 2
thing 3
thing' 1
thing' 2
thing' 3
thing :: Int -> IO ()
thing n = print $ n + cachedExpr
where
{-# NOINLINE cachedExpr #-}
cachedExpr :: Int
cachedExpr = unsafePerformIO $ do
putStrLn "computing cachedExpr..."
pure 5
thing' :: Int -> IO ()
thing' n = print $ n + cachedExpr'
{-# NOINLINE cachedExpr' #-}
cachedExpr' :: Int
cachedExpr' = unsafePerformIO $ do
putStrLn "computing cachedExpr'..."
pure 5
{-
% ghc -O0 NoInlineWhere.hs -o noinlinewhere && ./noinlinewhere
[1 of 1] Compiling Main ( NoInlineWhere.hs, NoInlineWhere.o )
Linking noinlinewhere ...
computing cachedExpr...
6
computing cachedExpr...
7
computing cachedExpr...
8
computing cachedExpr'...
6
7
8
% rm noinlinewhere NoInlineWhere.{hi,o}
% ghc -O2 NoInlineWhere.hs -o noinlinewhere && ./noinlinewhere
[1 of 1] Compiling Main ( NoInlineWhere.hs, NoInlineWhere.o )
Linking noinlinewhere ...
computing cachedExpr...
6
7
8
computing cachedExpr'...
6
7
8
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment