Skip to content

Instantly share code, notes, and snippets.

@jtobin
Created May 1, 2014 23:02
Show Gist options
  • Select an option

  • Save jtobin/b8ff5ef03855603bcb73 to your computer and use it in GitHub Desktop.

Select an option

Save jtobin/b8ff5ef03855603bcb73 to your computer and use it in GitHub Desktop.
Boy/Girl problem
module Main where
import Control.Monad
import Control.Monad.Primitive
import System.Environment
import System.Random.MWC
data Child = Boy | Girl deriving (Eq, Show)
instance Variate Child where
uniform g = do
z <- uniform g
return $ if z then Boy else Girl
uniformR (Girl,Boy) g = uniform g
uniformR (Girl,Girl) _ = return Girl
uniformR (Boy,Boy) _ = return Boy
uniformR (Boy,Girl) g = uniform g
generateChildren :: PrimMonad m => Gen (PrimState m) -> m [Child]
generateChildren g = replicateM 2 (uniform g)
simulate :: Int -> Gen RealWorld -> IO ()
simulate n g = do
cs <- replicateM n (generateChildren g)
let atLeastOneBoy = filter (elem Boy) cs
otherChildIsGirl = filter (elem Girl) atLeastOneBoy
fil xs = fromIntegral $ length xs
putStrLn $ "A) total pairs of simulated children: " ++ show n
putStrLn $ "B) pairs w/at least one boy: "
++ show (length atLeastOneBoy)
putStrLn $ "C) pairs w/at least one boy and other is girl: "
++ show (length otherChildIsGirl)
putStrLn $ "D) C as a proportion of B : "
++ show (fil otherChildIsGirl / fil atLeastOneBoy)
main :: IO ()
main = do
rawArgs <- getArgs
let n = case rawArgs of
[] -> error "USAGE: ./boygirl <number of pairs>"
(h:_) -> read h :: Int
withSystemRandom . asGenIO $ simulate n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment