Created
May 1, 2014 23:02
-
-
Save jtobin/b8ff5ef03855603bcb73 to your computer and use it in GitHub Desktop.
Boy/Girl problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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