Skip to content

Instantly share code, notes, and snippets.

@rarous
Last active December 14, 2015 12:58
Show Gist options
  • Save rarous/5090061 to your computer and use it in GitHub Desktop.
Save rarous/5090061 to your computer and use it in GitHub Desktop.
Reimplementation od Monty Hall problem in F#
let _rnd = System.Random()
let rand min max = _rnd.Next(min, max)
type Choice = | Yes | No
let addDoors = function
| (1, _) -> [| "dragon"; "goat"; "goat" |]
| (0, 1) -> [| "goat"; "dragon"; "goat" |]
| (0, 0) -> [| "goat"; "goat"; "dragon" |]
| (_, _) -> failwith "Option is out of range"
let openGoatDoor (doors: string array) =
let rec impl d =
match doors.[d] with
| "goat" -> d
| _ -> rand 0 3 |> impl
rand 0 3 |> impl
let montyHall switch doorNumber =
let doors = (rand 0 2, rand 0 2) |> addDoors
let rec openNotChoosenGoatDoor() =
match openGoatDoor doors with
| x when x = doorNumber -> openNotChoosenGoatDoor()
| x -> x
let goatDoor = openNotChoosenGoatDoor()
let nr =
match switch with
| No -> doorNumber
| _ -> Set.ofList [0 .. 2] - Set.ofList [goatDoor; doorNumber] |> Seq.exactlyOne
doors.[nr]
let testMontyHall playtimes switch =
[0 .. playtimes]
|> Seq.map (fun _ -> rand 0 3 |> montyHall switch)
|> Seq.countBy id
|> Seq.iter (printfn "%A")
testMontyHall 1000000 Yes
@rarous
Copy link
Author

rarous commented Mar 5, 2013

Pro srovnání imperativní implementace v Pythonu https://coderwall.com/p/fezbpa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment