Skip to content

Instantly share code, notes, and snippets.

@yihuang
Created November 24, 2015 02:51
Show Gist options
  • Select an option

  • Save yihuang/f24675aee03c99cd4a6c to your computer and use it in GitHub Desktop.

Select an option

Save yihuang/f24675aee03c99cd4a6c to your computer and use it in GitHub Desktop.
Try to observe evaluation process.
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (foldr, foldl, foldl')
import System.Mem(performGC)
import GHC.HeapView
instance Monoid Integer where
mappend = (+)
mempty = 0
foldr f z l = result
where
result = loop f z l
loop f z [] = observe result `seq` z
loop f z (x:xs) = observe result `seq` (x `f` loop f z xs)
foldl f z l = loop f z l
where
loop f z [] = observe l `seq` z
loop f z (x:xs) = let z' = z `f` x
in observe l `seq` (loop f z' xs)
l1 :: Integer
l1 = foldr (+) 0 [1..10]
l2 :: Integer
l2 = foldl (+) 0 [1..10]
observe :: Monoid a => a -> a
observe a = unsafePerformIO $ do
performGC
s <- ppHeapGraph <$> buildHeapGraph 1000 a (asBox a)
putStrLn s
return a
{-# NOINLINE observe #-}
main = do
print "======foldr=========="
print l1
print "======foldl=========="
print l2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment