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

Tim Chevalier catamorphism at gmail.com
Mon Nov 5 15:24:51 EST 2007


On 11/5/07, Alex Young <alex at blackkettle.org> wrote:
>
> randList :: Int -> [IO Int]
> randList n = randListTail [] n
>
> randPairs :: Int -> [(IO Int, IO Int)]
> randPairs n = zip (randList n) (randList n)
[snip]
>
> doCountPair :: (IO Int, IO Int) -> IO Int
> doCountPair (a, b) = do
>    x <- a
>    y <- b
>    return (pairIsInside x y)
>
> fSumListTail :: Int -> [(IO Int, IO Int)] -> IO Int
> fSumListTail total [] = do
>    return total
> fSumListTail total (x:xs) = do
>    y <- doCountPair x
>    fSumListTail (total+y) xs
>
> fSumList :: [(IO Int, IO Int)] -> IO Int
> fSumList l = fSumListTail 0 l
>

It's unusual to return a list of IO actions or to take a list of pairs
of IO actions as an argument. You should think about whether there's a
reason you're doing this. For example, why not rewrite randList as:

randList :: Int -> IO [Int]
randList n = sequence $ randListTail [] n

(for example)?

> piAsDouble :: Int -> Int -> Double
> piAsDouble a b =
>    (fromInteger (toInteger a)) / (fromInteger (toInteger b))
>

This can be rewritten as: fromIntegral a / fromIntegral b (I think --
not tested. The above isn't tested either.)

Those are just a couple things that jump out at me. fSumListTail looks
like it should be expressible using a foldM as well. In fact,
fSumListTail looks like it ought to be a pure function. Think about
how you can isolate the parts of the code that do IO so that most
functions are pure.

Cheers,
Tim

-- 
Tim Chevalier * catamorphism.org * Often in error, never in doubt
"Faith, faith is an island in the setting sun / But proof, yes, proof
is the bottom line for everyone."--Paul Simon


More information about the Haskell-Cafe mailing list