[Haskell-beginners] foldl' vs seq

Stephen Tetley stephen.tetley at gmail.com
Mon Feb 1 06:31:33 EST 2010


Hi Gabi

The seq is not forcing the strictness that you are expecting.

A tail recursive accumulator version is comparable to foldl' (I'm not
sure which other pieces out of the bag of strictness tricks deepseq,
etc would get the same results without the accumulator).

Best wishes

Stephen


All versions compiled with -O2...

module Main where


mySum :: [Integer] -> Integer
mySum xs0 = step 0 xs0 where
  step a []     = a
  step a (x:xs) = let a' = a+x in a' `seq` step a' xs

main = do
  putStrLn "mySum tail-rec:"
  putStrLn $ "mySum [1..10^6]:" ++ show (mySum [1..10^6])

-----------------

$ ./MySumTR.exe +RTS -sstderr -RTS
d:\coding\haskell\cafe\MySumTR.exe +RTS -sstderr
mySum tail-rec:
mySum [1..10^6]:500000500000
     100,439,096 bytes allocated in the heap
          16,572 bytes copied during GC
           3,276 bytes maximum residency (1 sample(s))
          11,944 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:   192 collections,     0 parallel,  0.00s,  0.00s elapsed
  Generation 1:     1 collections,     0 parallel,  0.00s,  0.00s elapsed

  INIT  time    0.02s  (  0.00s elapsed)
  MUT   time    0.33s  (  0.33s elapsed)
  GC    time    0.00s  (  0.00s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    0.34s  (  0.33s elapsed)

  %GC time       0.0%  (0.0% elapsed)

  Alloc rate    292,186,461 bytes per MUT second

  Productivity  95.5% of total user, 100.0% of total elapsed

-----------------------------

$ ./SeqFoldl.exe +RTS -sstderr -RTS
d:\coding\haskell\cafe\SeqFoldl.exe +RTS -sstderr
sum (foldl'):
sum [1..10^6]:500000500000
     100,438,952 bytes allocated in the heap
          16,572 bytes copied during GC
           3,276 bytes maximum residency (1 sample(s))
          11,944 bytes maximum slop
               1 MB total memory in use (0 MB lost due to fragmentation)

  Generation 0:   192 collections,     0 parallel,  0.03s,  0.03s elapsed
  Generation 1:     1 collections,     0 parallel,  0.00s,  0.00s elapsed

  INIT  time    0.02s  (  0.00s elapsed)
  MUT   time    0.30s  (  0.30s elapsed)
  GC    time    0.03s  (  0.03s elapsed)
  EXIT  time    0.00s  (  0.00s elapsed)
  Total time    0.34s  (  0.33s elapsed)

  %GC time       9.1%  (9.5% elapsed)

  Alloc rate    321,404,646 bytes per MUT second

  Productivity  86.4% of total user, 90.5% of total elapsed


More information about the Beginners mailing list