Mathias Verraes
May 04, 2016
2.4k

# The Monty Hall Problem with Haskell

5min lightning talk for the SoCraTes Belgium meetup.

May 04, 2016

## Transcript

1. The Monty Hall Problem
@mathiasverraes

2. Don't use
thinking
when you can use
programming
— Alan Turing1
1 Supposedly

3. data Door = Goat | Car
deriving (Eq, Show)
type Game = [Door]

4. newGame :: MonadRandom m => m Game
newGame = shuffleM [Car, Goat, Goat]
newGames :: MonadRandom m => m [Game]
newGames = replicateM 100 newGame

5. (|>) = flip (\$)
play :: Strategy -> Game -> Door
play strategy game =
game
|> pickDoor
|> revealGoat
|> strategy

6. pickDoor :: Game -> Game
pickDoor = id
-- Assume we always pick
-- the first door, it
-- doesn't matter anyway.

7. revealGoat :: Game -> Game
revealGoat [choice, Goat, x] = [choice, x]
revealGoat [choice, x, Goat] = [choice, x]

8. type Strategy = Game -> Door
stay :: Strategy
stay [firstChoice, alternative] = firstChoice
switch :: Strategy
switch [firstChoice, alternative] = alternative

9. do
game <- newGame
return \$ play stay game)
-- Goat
do
game <- newGame
return \$ play switch game
-- Car

10. playAll :: Strategy -> [Game] -> Int
playAll strategy games =
map (play strategy) games
|> filter (==Car)
|> length

11. do
gs <- newGames
return \$ playAll stay gs
-- 32
do
gs <- newGames
return \$ playAll switch gs
-- 68

12. 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
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

13. Full source code:
https://gist.github.com/mathiasverraes/