`Data.Map.Strict.foldr'` strictness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- To build: | |
-- ghc -package ghc-heap-view -package containers Main.hs | |
-- | |
{-# LANGUAGE BangPatterns #-} | |
import Control.Exception (evaluate) | |
import Data.Map (Map) | |
import Data.Map.Internal (Map (..)) | |
import qualified Data.Map.Strict as Map | |
import qualified Debug.Trace as Debug | |
import qualified GHC.HeapView as HeapView | |
import qualified GHC.HeapView.Debug as HeapView | |
-- | Like the original 'Map.foldr'', but even more strict! | |
-- | |
foldr' :: (a -> b -> b) -> b -> Map k a -> b | |
foldr' f = go | |
where | |
go !z Tip = z | |
go z (Bin _ _ x l r) = go (f x $! go z r) l | |
main :: IO () | |
main = do | |
putStrLn "\n*** Map.foldr' ***\n" | |
evaluate y0 | |
HeapView.buildHeapTree 100 (HeapView.asBox y0) | |
>>= print .HeapView.ppHeapTree | |
putStrLn "\n*** Map.foldr' & seq ***\n" | |
evaluate y1 | |
HeapView.buildHeapTree 100 (HeapView.asBox y1) | |
>>= print . HeapView.ppHeapTree | |
putStrLn "\n*** foldr' ***" | |
evaluate y2 | |
HeapView.buildHeapTree 100 (HeapView.asBox y2) | |
>>= print . HeapView.ppHeapTree | |
putStrLn "\n*** Map.foldl ***" | |
evaluate y3 | |
HeapView.buildHeapTree 100 (HeapView.asBox y3) | |
>>= print . HeapView.ppHeapTree | |
putStrLn "\n*** Map.foldl' ***" | |
evaluate y4 | |
HeapView.buildHeapTree 100 (HeapView.asBox y4) | |
>>= print . HeapView.ppHeapTree | |
where | |
x0, x1, x2, x3, x4 :: Map Int Int | |
y0, y1, y2, y3, y4 :: [Int] | |
x0 = Map.fromList ((\x -> (x, x)) `map` [1..10]) | |
x1 = Map.fromList ((\x -> (x, x)) `map` [1..10]) | |
x2 = Map.fromList ((\x -> (x, x)) `map` [1..10]) | |
x3 = Map.fromList ((\x -> (x, x)) `map` [1..10]) | |
x4 = Map.fromList ((\x -> (x, x)) `map` [1..10]) | |
y0 = Map.foldr' (:) [] x0 | |
y1 = let r = Map.foldr' (:) [] x1 | |
in length r `seq` r | |
y2 = foldr' (:) [] x2 | |
y3 = Map.foldl (flip (:)) [] x3 | |
y4 = Map.foldl' (flip (:)) [] x4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment