Mathias Verraes
May 04, 2016
2.5k

# The Monty Hall Problem with Haskell

5min lightning talk for the SoCraTes Belgium meetup.

May 04, 2016

## Transcript

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 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
13. ### 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/