Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Monty Hall Problem with Haskell

The Monty Hall Problem with Haskell

5min lightning talk for the SoCraTes Belgium meetup.

Mathias Verraes

May 04, 2016
Tweet

More Decks by Mathias Verraes

Other Decks in Technology

Transcript

  1. newGame :: MonadRandom m => m Game newGame = shuffleM

    [Car, Goat, Goat] newGames :: MonadRandom m => m [Game] newGames = replicateM 100 newGame
  2. (|>) = flip ($) play :: Strategy -> Game ->

    Door play strategy game = game |> pickDoor |> revealGoat |> strategy
  3. pickDoor :: Game -> Game pickDoor = id -- Assume

    we always pick -- the first door, it -- doesn't matter anyway.
  4. revealGoat :: Game -> Game revealGoat [choice, Goat, x] =

    [choice, x] revealGoat [choice, x, Goat] = [choice, x]
  5. type Strategy = Game -> Door stay :: Strategy stay

    [firstChoice, alternative] = firstChoice switch :: Strategy switch [firstChoice, alternative] = alternative
  6. do game <- newGame return $ play stay game) --

    Goat do game <- newGame return $ play switch game -- Car
  7. playAll :: Strategy -> [Game] -> Int playAll strategy games

    = map (play strategy) games |> filter (==Car) |> length
  8. do gs <- newGames return $ playAll stay gs --

    32 do gs <- newGames return $ playAll switch gs -- 68
  9. module MontyHall where newGame :: MonadRandom m => m Game

    newGame = shuffleM [Car, Goat, Goat] import System.Random.Shuffle newGames :: MonadRandom m => m [Game] import Control.Monad.Random.Class newGames = replicateM 100 newGame import Control.Monad pickDoor :: Game -> Game (|>) = flip ($) pickDoor = id data Door = Goat | Car deriving (Eq, Show) revealGoat :: Game -> Game type Game = [Door] revealGoat [choice, Goat, x] = [choice, x] type Strategy = Game -> Door revealGoat [choice, x, Goat] = [choice, x] play :: Strategy -> Game -> Door stay, switch :: Strategy play strategy game = stay [firstChoice, alternative] = firstChoice game switch [firstChoice, alternative] = alternative |> pickDoor |> revealGoat main :: IO() |> strategy main = do (stayCnt, switchCnt) <- do playAll :: Strategy -> [Game] -> Int gs <- newGames playAll strategy games = return (playAll stay gs, playAll switch gs) map (play strategy) games print ("Stay: " ++ show stayCnt) |> filter (==Car) print ("Switch: " ++ show switchCnt) |> length
  10. Full source code: https://gist.github.com/mathiasverraes/ 3a31c912c6efb496566d55ee077dad6f Diagram: Curiouser http://www.curiouser.co.uk/monty/montyhall2.htm Images: AsapScience

    http://youtube.com/watch?v=9vRUxbzJZ9Y Inspiration: F# Monty Hall problem by Yan Cui http://theburningmonk.com/2015/09/f-monty-hall-problem/