praxis

Various programming exercises.
Log | Files | Refs

commit 2e321fc7c01f52f4325bf7bffd450cf0c07f0621
parent 949a0ad5e1180ce8a9f8afbbb230a55099df6dae
Author: Jared Tobin <jared@jtobin.ca>
Date:   Sat,  7 Jul 2018 13:12:18 +1200

Add pi estimating exercise.

Diffstat:
A20180705_estimate_pi/Pi.hs | 37+++++++++++++++++++++++++++++++++++++
M20180706_scores/Scores.hs | 6++++++
2 files changed, 43 insertions(+), 0 deletions(-)

diff --git a/20180705_estimate_pi/Pi.hs b/20180705_estimate_pi/Pi.hs @@ -0,0 +1,37 @@ +{-# OPTIONS_GHC -Wall -fno-warn-type-defaults #-} +{-# LANGUAGE ScopedTypeVariables #-} + +import Control.Monad.Primitive (PrimMonad, PrimState) +import System.Random.MWC as MWC +import qualified Control.Foldl as L +import Pipes ((>->)) +import qualified Pipes as P +import qualified Pipes.Prelude as P + +sample :: forall m. PrimMonad m => Gen (PrimState m) -> P.Producer Bool m () +sample prng = do + val <- P.lift (relPrime prng) + P.yield val + sample prng + where + relPrime rng = + rprime <$> (uniform rng :: m Word) <*> (uniform rng :: m Word) + + rprime a b = gcd a b == 1 + +count :: Num a => L.Fold Bool a +count = L.Fold alg 0 id where + alg acc tru + | tru = acc + 1 + | otherwise = acc + +avg :: Fractional a => L.Fold Bool a +avg = (/) <$> count <*> L.genericLength + +main :: IO () +main = do + prng <- createSystemRandom + freq <- L.purely P.fold avg (sample prng >-> P.take 1000000) + + print (sqrt (6 / freq)) + diff --git a/20180706_scores/Scores.hs b/20180706_scores/Scores.hs @@ -51,6 +51,12 @@ test = [ , ("Rachel", 99) , ("Rachel", 100) , ("Rachel", 81) + , ("Deanie", 99) + , ("Deanie", 75) + , ("Deanie", 76) + , ("Deanie", 74) + , ("Deanie", 43) + , ("Deanie", 69) ] main :: IO ()