Skip to content

Instantly share code, notes, and snippets.

@mastoj
Created July 14, 2020 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastoj/50f6b6eac328be0b2d62904b767e37c9 to your computer and use it in GitHub Desktop.
Save mastoj/50f6b6eac328be0b2d62904b767e37c9 to your computer and use it in GitHub Desktop.
type Connection = {
Start: unit -> unit
Stop: unit -> unit
}
type ActiveConnection = {
Stop: unit -> ConnectionWrapper
}
and InActiveConnection = {
Start: unit -> ConnectionWrapper
}
and ConnectionWrapper =
| InActive of InActiveConnection
| Active of ActiveConnection
with
static member Create() =
let connection = {
Start = (fun () -> printfn "Starting")
Stop = (fun () -> printfn "Stopping")
}
let rec start () =
connection.Start()
Active {
Stop = stop
}
and stop () =
connection.Stop()
InActive {
Start = start
}
InActive { Start = start }
let mutable conn = ConnectionWrapper.Create()
let startClick() =
conn <-
match conn with
| InActive inActiveConn -> inActiveConn.Start()
| Active _ -> printfn "Already started"; conn
let stopClick() =
conn <-
match conn with
| InActive _ -> printfn "Already closed"; conn
| Active activeConn -> activeConn.Stop()
startClick() // Prints "Starting"
startClick() // Prints "Already started"
stopClick() // Prints "Stopping"
stopClick() // Prints "Already stopped"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment