Don Stewart wrote:
alex:
<snip>
You can replace most of your loops with Data.List functions, and
simplify the code overall by threading around a lazy list of randoms,
rather than calling into IO all the time:

    import System.Random
    import System.Environment
    import Data.List
    import Control.Monad

    randMax    = 32767
    unitRadius = randMax * randMax

    countPair :: (Int, Int) -> Int
    countPair (x, y) = fromEnum (x*x + y*y < unitRadius)

    calculatePi total g = fromIntegral (4*count) / fromIntegral total
     where
      count = sum
            . map countPair
            . take total
            $ zip (randomRs (0,randMax) a)
I wish I'd known about randomRs a couple of hours ago :-)

                  (randomRs (0,randMax) b)

      (a,b) = split g

    main = do
      [v] <- getArgs
      g <- newStdGen
      print $ calculatePi (read v) g

Compiled like so:

    $ ghc -O2 A.hs -o A

    $ time ./A 100000
    3.13548
    ./A 100000  0.08s user 0.02s system 98% cpu 0.101 total

We get no stack overflow.
Not with -O2, but:

C:\Users\Alex\Documents\HaskellLearning\MonteCarlo>ghc BetterPi.hs

C:\Users\Alex\Documents\HaskellLearning\MonteCarlo>main.exe 1000000
Stack space overflow: current size 8388608 bytes.
Use `+RTS -Ksize' to increase it.

But:

C:\Users\Alex\Documents\HaskellLearning\MonteCarlo>ghc -O2 BetterPi.hs

C:\Users\Alex\Documents\HaskellLearning\MonteCarlo>main.exe 1000000
3.140636

This is a little confusing.  Is there a simple explanation for this
behaviour, or is it just a matter of "always use -O2 unless there's a
reason not to?"

Thanks - I really appreciate the explanations.

(P.S. Again - sorry for the duplication. I really need to watch my mail client more closely :-)

--
Alex
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to