Skip to content

Instantly share code, notes, and snippets.

@baronfel
Created May 25, 2021 21:59
Show Gist options
  • Save baronfel/b42a317899949492f177f893a3d416ed to your computer and use it in GitHub Desktop.
Save baronfel/b42a317899949492f177f893a3d416ed to your computer and use it in GitHub Desktop.
type AsyncOptionBuilder() =
member __.Return (value: 'T) : Async<Option<'T>> =
async { return Some value }
member __.ReturnFrom
(asyncResult: Async<Option<_>>)
: Async<Option<_>> =
asyncResult
member __.ReturnFrom
(result: Option<_>)
: Async<Option<_>> =
async.Return result
member __.Source(r: Result<'t, _>) = async { match r with Ok a -> return Some a | Error _ -> return None }
member __.Source(a: Async<'t>) = async {
let! inner = a
return Some inner
}
member __.Bind
(asyncResult: Async<Option<_>>, binder: 'T -> Async<Option<_>>)
: Async<Option<_>> =
async {
let! result = asyncResult
match result with
| Some x -> return! binder x
| None -> return None
}
let asyncOption = new AsyncOptionBuilder()
async {
// Example 1
let expected = Some 42
let! actual = asyncOption {
let! value = async.Return(42)
return value
}
printf "%A equals %A = %b" expected actual (expected = actual)
// Example 2
let expected = Some 42
let! actual = asyncOption {
let! value = async.Return(42)
return value
}
printf "%A equals %A = %b" expected actual (expected = actual)
} |> Async.Start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment