[ create a new paste ] login | about

Link: http://codepad.org/yXZMQC5A    [ raw code | output | fork ]

azumih - Haskell, pasted on Mar 10:
#! /usr/bin/env runghc
-- simplistic Monty Hall simulator

import System.Random
import Control.Monad

montyHall :: Bool -> IO Int
montyHall sw = do
    car     <- randomRIO (0::Int, 2::Int)
    iniSel  <- randomRIO (0::Int, 2::Int)
    opened  <- montyOpensGoatDoor car iniSel
    if sw 
        then
            return $ if (switch iniSel opened) == car then 1 else 0
        else
            return $ if iniSel == car then 1 else 0


montyOpensGoatDoor :: Int -> Int -> IO Int
montyOpensGoatDoor car sel = do
    idx <- randomRIO (0, (length cand) - 1)
    return $ cand !! idx
    where
        cand = [x | x <- [0, 1, 2], x /= car, x /= sel]


switch :: Int -> Int -> Int
switch ini open = head [x | x <- [0, 1, 2], x /= ini, x /= open]


addm :: Monad m => m Int -> m Int -> m Int
addm a b = do
    x <- a
    y <- b
    return (x + y)

main = do
    sw <- foldr addm (return 0) $ take 2000 . repeat $ montyHall True
    st <- foldr addm (return 0) $ take 2000 . repeat $ montyHall False
    print $ "switch: " ++ show sw
    print $ "stay:   " ++ show st


Output:
1
2
"switch: 1336"
"stay:   668"


Create a new paste based on this one


Comments: