fork download
  1. module Main where
  2.  
  3. import Data.Array (Array, accumArray, elems, Ix, inRange)
  4. import System.Random (RandomGen, newStdGen, random)
  5. import Control.Monad.State (State, state, evalState)
  6.  
  7. histogram :: Ix i => (i, i) -> [i] -> Array i Int
  8. histogram bounds bins = accumArray (+) 0 bounds [(x, 1) | x <- bins, inRange bounds x]
  9.  
  10. bernoulli :: RandomGen gen => Double -> State gen Int
  11. bernoulli p =
  12. do x <- state random
  13. return $ if x < p then 1 else 0
  14.  
  15. binomial :: RandomGen gen => Int -> Double -> State gen Int
  16. binomial count p =
  17. do ns <- sequence $ replicate count $ bernoulli p
  18. return $ sum ns
  19.  
  20. simulate :: RandomGen gen => gen -> Int -> State gen a -> [a]
  21. simulate gen tries m = evalState (sequence $ replicate tries m) gen
  22.  
  23. test :: Double -> Int -> Int -> IO ()
  24. test bias nails tries =
  25. do gen <- newStdGen
  26. let bins = simulate gen tries $ binomial nails bias
  27. let h = histogram (0, nails) bins
  28. print $ elems h
  29.  
  30. main :: IO ()
  31. main = test 0.5 100 10000
  32.  
Success #stdin #stdout 2.43s 4988KB
stdin
Standard input is empty
stdout
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,7,16,31,49,68,111,153,220,281,364,500,581,650,718,811,812,796,726,661,565,503,427,310,207,169,88,72,39,21,25,6,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]