praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Pi.hs (860B)


      1 {-# OPTIONS_GHC -Wall -fno-warn-type-defaults #-}
      2 
      3 import qualified Control.Foldl as L
      4 import Control.Monad.Primitive
      5 import Pipes ((>->))
      6 import qualified Pipes as P
      7 import qualified Pipes.Prelude as P
      8 import System.Random.MWC as MWC
      9 
     10 sample
     11   :: PrimMonad m
     12   => Gen (PrimState m)
     13   -> P.Producer Bool m ()
     14 sample prng = do
     15     m <- P.lift (uniform prng)
     16     n <- P.lift (uniform prng)
     17     P.yield (rprime m n)
     18     sample prng
     19   where
     20     rprime :: Word -> Word -> Bool
     21     rprime a b = gcd a b == 1
     22 
     23 count :: Num a => L.Fold Bool a
     24 count = L.Fold alg 0 id where
     25   alg acc tr
     26     | tr = acc + 1
     27     | otherwise = acc
     28 
     29 avg :: Fractional a => L.Fold Bool a
     30 avg = (/) <$> count <*> L.genericLength
     31 
     32 main :: IO ()
     33 main = do
     34   prng <- createSystemRandom
     35 
     36   let pipe = sample prng >-> P.take (10 ^ 6)
     37   freq <- L.purely P.fold avg pipe
     38 
     39   print (sqrt (6 / freq))
     40