Skip to content

Instantly share code, notes, and snippets.

@dsyme
Created June 22, 2022 13:33
Show Gist options
  • Save dsyme/bda86cf2c2898a44cbc40f923ecb3afc to your computer and use it in GitHub Desktop.
Save dsyme/bda86cf2c2898a44cbc40f923ecb3afc to your computer and use it in GitHub Desktop.
open System
open System.Threading
type Cancellable<'T> = delegate of CancellationToken -> 'T
type CancellableBuilder() =
member _.Delay(body: unit -> Cancellable<'T>) =
Cancellable(fun ct ->
let computation = body()
computation.Invoke(ct))
member _.Bind(computation1: Cancellable<'T>, continuation: 'T -> Cancellable<'TResult>) =
Cancellable(fun ct ->
let v1 = computation1.Invoke(ct)
let computation2 = continuation v1
computation2.Invoke(ct))
member _.Return(v: 'T) =
Cancellable(fun ct -> v)
let cancellable = CancellableBuilder()
let f1() =
cancellable {
System.Console.WriteLine("hello")
return 4
}
let f2() =
cancellable {
System.Console.WriteLine("world")
return 5
}
let f3() =
cancellable {
let! v1 = f1()
let! v2 = f2()
return v1 + v2
}
let computation = f3()
let result = computation.Invoke(CancellationToken.None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment