Skip to main content

Hundred Doors Exercise

Jake Russo

Jake Russo

Quarrel Designer

As another exercise, I am going to be translating the 100 doors rosetta code example written in Standard ML.

datatype Door = Closed | Opened
fun toggle Closed = Opened
| toggle Opened = Closed
fun pass (steps, doors) = List.mapi (fn (k, door) => if (k+1) mod steps = 0 then toggle door else door) doors
(* [1..n] *)
fun runs n = List.tabulate (n, fn k => k+1)
fun run n =
let
val initialdoors = List.tabulate (n, fn _ => Closed)
val runs = runs n
in
foldl pass initialdoors runs
end
fun opened_doors n = List.mapPartiali (fn (k, Closed) => NONE | (k, Opened) => SOME (k+1)) (run n)
Door ?= Closed{} | Opened{}
toggle .= {Closed{}} => Opened()
toggle[+] .= {Opened{}} => Closed()
skip .= {Door? d} => d
pass .= {steps, doors} => (
[1::doors[@]] +> doors -> {k, door} =>
k %% steps @@ toggle door ~@ skip door
)
run .= {n} => (
initialDoors .= [1::n] -> Closed()
runs .= [1::n]
runs >- pass -> initialDoors
)
openedDoors .= {n} => (r .= run n; [1::r[@]] +> r) $> {k, Opened{}} => k