[Haskell-cafe] Monte Carlo Pi calculation (newbie learnings)

Don Stewart dons at galois.com
Tue Nov 6 18:56:27 EST 2007


lrpalmer:
> On Nov 5, 2007 8:11 PM, Alex Young <alex at blackkettle.org> wrote:
> > {--------------------------------------------------}
> > module Main where
> >
> > import Random
> > import System.Environment
> > import List
> > import Monad
> >
> > randMax = 32767
> > unitRadius = randMax * randMax
> >
> > rand :: IO Int
> > rand = getStdRandom (randomR (0, randMax))
> >
> > randListTail accum 0 = accum
> > randListTail accum n = randListTail (rand : accum) (n - 1)
> 
> I can't believe that nobody has pointed this out yet.  I think we were
> all focused on your weird usage of the IO monad...
> 
> Anyway, you do not want to use tail recursion in this case.  Here you
> have to evaluate everything before you can return the first element,
> because we don't know that you're going to return accum when you get
> down to zero... you might return 1:accum or something.  When you're
> returning a list, it's best not to use tail recursion because we can
> get the initial elements of the list lazily.
> 
> randList 0 = []
> randList n = rand : randList (n-1)
> 
> Is a much better implementation in Haskell.
> 
> But that's usually just spelled "replicate n rand".  :-)
> 

I did suggest: take n randomrRs :) 

-- Don


More information about the Haskell-Cafe mailing list