2

To run in constant space, mean2 uses sumlen2 which seqs summation and count. But again my belief and textbook, mean2 still runs with space leak. What's the mistake?

Any helps will be appreciated deeply.

-- Thinking Functionally with Haskell by R. Bird
-- Chapter 7.2 Controlling space

sumlen1 = foldl' g (0,0)
  where g (s,n) x = (s+x,n+1)

sumlen2 = foldl' g (0,0)
  where g (s,n) x = s `seq` n `seq` (s+x,n+1)

-- has space leak
mean1 [] = 0
mean1 xs = s / fromIntegral n
  where (s,n) = sumlen1 xs        

-- should run in constant space    
mean2 [] = 0
mean2 xs = s / fromIntegral n
  where (s,n) = sumlen2 xs        

λ> mean1 [1..1000000]
500000.5
(1.99 secs, 520,962,648 bytes)
λ> mean2 [1..1000000]
500000.5
(1.36 secs, 516,288,128 bytes)
Chul-Woong Yang
  • 1,223
  • 10
  • 17
  • 2
    Can't see the issue, but is that "bytes" the total bytes allocated or the peak allocation. Perhaps it's the former, in which case `sumlen2` is running in constant space. – Clinton Mar 14 '16 at 04:10
  • 1
    Thank you. I've regarded `bytes` as peak allocation, However it's the total bytes allocated. `sumlen2` runs with constant space – Chul-Woong Yang Mar 14 '16 at 04:26
  • For performance measurements be sure to compile your code with `ghc -O2`. The GHCi interpreter does not optimize as much. – chi Mar 14 '16 at 11:01

1 Answers1

1

As @Clinton commented out, the performance metrics from ghci is the total bytes allocation. sumlen2 runs with constant space.

Chul-Woong Yang
  • 1,223
  • 10
  • 17