praxis

Various programming exercises.
Log | Files | Refs

commit 9cdb52e7c7113925b6f6b96ae95afb18ad80f4ea
parent 1d4a17fa529d674476b4b84fd3195afc7ce0e966
Author: Jared Tobin <jared@jtobin.ca>
Date:   Sat,  7 Jul 2018 13:31:05 +1200

Simplify.

Diffstat:
M20180705_estimate_pi/Pi.hs | 21++++++++++++++-------
1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/20180705_estimate_pi/Pi.hs b/20180705_estimate_pi/Pi.hs @@ -1,25 +1,30 @@ {-# OPTIONS_GHC -Wall -fno-warn-type-defaults #-} -import Control.Monad.Primitive (PrimMonad, PrimState) -import System.Random.MWC as MWC import qualified Control.Foldl as L +import Control.Monad.Primitive import Pipes ((>->)) import qualified Pipes as P import qualified Pipes.Prelude as P +import System.Random.MWC as MWC sample :: PrimMonad m - => Gen (PrimState m) -> P.Producer Bool m () + => Gen (PrimState m) + -> P.Producer Bool m () sample prng = do - val <- P.lift (rprime <$> uniform prng <*> uniform prng) - P.yield val + m <- P.lift (uniform prng) + n <- P.lift (uniform prng) + P.yield (rprime m n) sample prng where rprime :: Word -> Word -> Bool rprime a b = gcd a b == 1 count :: Num a => L.Fold Bool a -count = L.Fold (\acc tr -> if tr then acc + 1 else acc) 0 id +count = L.Fold alg 0 id where + alg acc tr + | tr = acc + 1 + | otherwise = acc avg :: Fractional a => L.Fold Bool a avg = (/) <$> count <*> L.genericLength @@ -27,7 +32,9 @@ avg = (/) <$> count <*> L.genericLength main :: IO () main = do prng <- createSystemRandom - freq <- L.purely P.fold avg (sample prng >-> P.take 1000000) + + let pipe = sample prng >-> P.take (10 ^ 6) + freq <- L.purely P.fold avg pipe print (sqrt (6 / freq))