[Haskell-cafe] Re: Looking for the fastest Haskell primes

Daniel Fischer daniel.is.fischer at web.de
Thu Apr 16 05:05:53 EDT 2009

Am Donnerstag 16 April 2009 10:41:43 schrieb Niemeijer, R.A.:
> Heinrich Apfelmus wrote:
> > +1 except that exporting the potentially infinite list of primes is
> > problematic in that it may become a memory leak.
> >
> > I'd suggest to export two versions
> >
> >   primes  :: [Integer]
> >   primes' :: () -> [Integer]
> >
> > for casual (i.e. throwaway program to solve a Project Euler problem) and
> > for memory aware use respectively.
> I'm afraid I don't quite follow. Would you mind explaining what the first
> parameter is for and how it would solve the memory leak?

If your programme uses primes some time early and again at the end, the list of primes 
(calculated so far) is kept in memory, because it's a top level constant (CAF). If you 
don't need the primes in between, calculate many of them at the start and use only a few 
at the end, that's a terrible memory-waste. If you don't use primes later, it *may* be 
that they're garbage-collected, but I wouldn't count on it.

primes' is a function, so the list of primes is calculated anew every time you use 
primes' ()
in your programme and garbage collected when the programme leaves that use site.

Which behaviour is desired depends of course on the programme.

More information about the Haskell-Cafe mailing list