seq强制评估

时间:2016-03-14 03:37:27

标签: haskell lazy-evaluation

要在常量空间中投放,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)

1 个答案:

答案 0 :(得分:1)

正如@Clinton所述,ghci的性能指标是总字节数分配。 android.util.Pair以恒定的空间运行。