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

Luke Palmer lrpalmer at gmail.com
Tue Nov 6 18:55:02 EST 2007


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".  :-)

Luke


More information about the Haskell-Cafe mailing list