[Haskell-cafe] Generating a random list

Bryan O'Sullivan bos at serpentine.com
Sat Mar 1 02:21:10 EST 2008


Milos Hasan wrote:

> so let's say I want to generate a list of N random floats. The elegant
> way of doing it would be to create an infinite lazy list of floats and
> take the first N, but for N = 1,000,000 or more, this overflows the
> stack. The reason is apparently that the take function is not
> tail-recursive, and so it uses O(N) stack space..

You might want to post your code.  The reason take isn't tail recursive
is that it will be evaluated lazily, so it will not consume O(n) stack
space.

However, using take is the wrong approach anyway, as the user of the
random numbers needs to return the unconsumed portion of the list so
that the next user can consume them.  This is why code that uses random
numbers is usually written in the context of a state monad, such as
MonadRandom: http://www.haskell.org/haskellwiki/New_monads/MonadRandom

	<b


More information about the Haskell-Cafe mailing list