Skip to content

Instantly share code, notes, and snippets.

@throughnothing
Last active June 10, 2020 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save throughnothing/f165f6d1fb3efd1ff854aad4ea79d82b to your computer and use it in GitHub Desktop.
Save throughnothing/f165f6d1fb3efd1ff854aad4ea79d82b to your computer and use it in GitHub Desktop.
Monty Hall
module MontyHall.Main where
import Prelude
import Data.Foldable (foldr)
import Data.List.Lazy (range)
import Data.Tuple (Tuple(..))
import Debug.Trace (class DebugWarning, spy)
import Effect (Effect)
import Effect.Random (randomInt)
data Stage = Stage1 | Stage2 | Stage3
data Pos = One | Two | Three
type Stats = { games :: Int, swapWins :: Int, noSwapWins :: Int}
randomPos :: Effect Pos
randomPos = do
r <- randomInt 1 3
pure $ toPos r
where
toPos :: Int -> Pos
toPos i
| i == 1 = One
| i == 2 = Two
| otherwise = Three
mkStage :: Pos -> Stage
mkStage One = Stage1
mkStage Two = Stage2
mkStage Three = Stage3
-- | Given a stage, and a guess, return whether swapping wins or not
simulateSwap :: Stage -> Pos -> Boolean
simulateSwap Stage1 One = false
simulateSwap Stage1 _ = true
simulateSwap Stage2 Two = false
simulateSwap Stage2 _ = true
simulateSwap Stage3 Three = false
simulateSwap Stage3 _ = true
-- | Given a stage, and a guess, return whether swapping wins or not
simulateNoSwap :: Stage -> Pos -> Boolean
simulateNoSwap Stage1 One = true
simulateNoSwap Stage1 _ = false
simulateNoSwap Stage2 Two = true
simulateNoSwap Stage2 _ = false
simulateNoSwap Stage3 Three = true
simulateNoSwap Stage3 _ = false
test :: DebugWarning => Effect Stats
test = do
ls <- foldr (const (_ >>= tally)) (pure {games: 0, swapWins: 0, noSwapWins: 0}) $ range 1 9999
pure $ spy "Output: " ls
where
simulate :: Effect (Tuple Boolean Boolean)
simulate = do
stage <- map mkStage randomPos
guess <- randomPos
pure $ Tuple (simulateSwap stage guess) (simulateNoSwap stage guess)
tally :: Stats -> Effect Stats
tally s = do
res <- simulate
case res of
Tuple true false -> pure { games: s.games + 1, swapWins: s.swapWins + 1, noSwapWins: s.noSwapWins }
Tuple false true -> pure { games: s.games + 1, swapWins: s.swapWins, noSwapWins: s.noSwapWins + 1}
Tuple _ _ -> pure { games: 0, swapWins: 0, noSwapWins: 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment