[Haskell-cafe] multiple computations, same input

Neil Mitchell ndmitchell at gmail.com
Mon Mar 27 17:31:00 EST 2006


Hi Greg,

> But if I do something like this:
>       f lst = show (filter (> 1) lst, filter (> 2) lst)
> then it looks like GHC won't garbage collect list elements
> until the first
> filter has completely finished

There is a very good reason for this, show (a,b) is essentially

show (a,b) = "(" ++ show a ++ ", " ++ show b ++ ")"

so all the elements of a are shown first, which means that lst is held
up in a thunk of filter, to be evaluated later. In this particular
case, you know that not (>2) implies not (>1) so you can speed it up
with:

f lst = show (part1, part2)
   where
       part1 = filter (>1) lst
       part2 = fitler (>2) part1

note that part2 only examines part1. As long as part1 is smaller than
lst, this will reduce the space leak.

There is really no way to "eliminate" the space leak in this
circumstance, since you really do need to hold a part of the data in
memory while you show the first one, so you can then show the second
one.

Thanks

Neil


More information about the Haskell-Cafe mailing list