Skip to content

Instantly share code, notes, and snippets.

@pocketberserker
Last active November 20, 2016 05:11
Show Gist options
  • Save pocketberserker/2f7d9a46dd36876fab0154400eea588c to your computer and use it in GitHub Desktop.
Save pocketberserker/2f7d9a46dd36876fab0154400eea588c to your computer and use it in GitHub Desktop.
type FlowControl = Break | Continue
type AsyncBuilder internal () =
member __.Zero<'T>() = async.Return((Unchecked.defaultof<'T>, Continue))
member __.Return(x) = async.Return((x, Break))
member this.ReturnFrom(x: Async<_>) = async.Bind(x, fun x -> this.Return(x))
member __.Bind(x, f) = async.Bind(x, f)
member this.Using(x, f) = async.Using(x, f)
member this.Combine(x, y) =
async.Bind(
x,
fun (x, cont) ->
match cont with
| Break -> async.Return((x, Break))
| Continue -> y
)
member this.While(guard, prog) =
if not (guard ()) then this.Zero()
else this.Combine(prog, async.Bind(this.Zero(), fun _ -> this.While(guard, prog)))
member this.For(xs: #seq<_>, f) =
this.Using(
xs.GetEnumerator(),
fun itor -> this.While(itor.MoveNext, async.Delay(fun () -> f itor.Current)))
member this.Delay(f) = async.Delay(f)
member this.Run(v: Async<_ * FlowControl>) = async.Bind(v, fun (x, _) -> async.Return(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment