Reputation: 1243
To run in constant space, mean2
uses sumlen2
which seq
s 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)
Upvotes: 2
Views: 96
Reputation: 1243
As @Clinton commented out, the performance metrics from ghci is the total bytes allocation. sumlen2
runs with constant space.
Upvotes: 1