Another space leak question
2 Jul 2001 10:14:58 -0000
"Srineet" <email@example.com> writes:
> Now [main2] continues forever, but doesn't cause hugs to run out of
> heap.What' the reason that, while both [main1] and [main2] run forever, the
> first causes hugs to run out of heap while second doesn't.
referring to the following program (slightly adapted for compatibility with
> step1 :: [Int] -> Int -> Int
> step1 (x:xs) n = step1 xs (n+x)
> main1 :: Int
> main1 = step1 (repeat 1) 1
> step2 :: [Int] -> Int -> Int
> step2 (x:xs) n | n == 0 = 0
> | otherwise = step2 xs (n+x)
> main2 :: Int
> main2 = step2 (repeat 1) 1
The reason is that the addition in step1 is deferred lazily,
since its result is never needed.
Therefore, unreduced additions accumulate.
In contrast, the result of the addition in step2 is needed
for comparison in ``n == 0'' --- this forces evaluation of n.
I have produced two animations (hold down the space bar in ghostview
to get the effect ;-), available at:
A remedy might be to force sequentialisation:
> step1' (x:xs) n = let n' = n+x in n' `seq` step1 xs n'
Hope that helps!