[Haskell-cafe] infinite list of random elements

Lennart Augustsson lennart at augustsson.net
Tue Jul 31 16:37:46 EDT 2007


Well, I don't know how many generators you need.  But I'm sure you can pass
them around in a way that doesn't leak.

On 7/31/07, Chad Scherrer <chad.scherrer at gmail.com> wrote:
>
> Ok, that looks good, but what if I need some random values elsewhere
> in the program? This doesn't return a new generator (and it can't
> because you never get to the end of the list). Without using IO or ST,
> you'd have to thread the parameter by hand or use the State monad,
> right? This is where I was leaking space before.
>
> Actually, this makes me wonder... I think what killed it before was
> that the state was threaded lazily through the various (= very many)
> calls. I suppose a State' monad, strict in the state, could help here.
> I wonder how performance for this would compare with IO or ST. Might
> have to try that sometime...
>
> Chad
>
> On 7/31/07, Lennart Augustsson <lennart at augustsson.net> wrote:
> > No leak in sight.
> >
> >   -- Lennart
> >
> > import Random
> > import Array
> >
> > randomElts :: RandomGen g => g -> [a] -> [a]
> > randomElts _ [] = []
> > randomElts g xs = map (a!) rs
> >    where a = listArray (1, n) xs
> >         rs = randomRs (1, n) g
> >      n = length xs
> >
> > main = do
> >     g <- getStdGen
> >     let xs = randomElts g [10,2,42::Int]
> >     print $ sum $ take 1000000 xs
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070731/02d17782/attachment.htm


More information about the Haskell-Cafe mailing list