要在常量空间中投放,mean2
使用sumlen2
总和{count}的seq
。但是,我的信念和教科书mean2
仍然在空间泄漏的情况下运行。这是什么错误?
任何帮助都将深受赞赏。
-- 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)
答案 0 :(得分:1)
正如@Clinton所述,ghci的性能指标是总字节数分配。 android.util.Pair
以恒定的空间运行。