1 people like it.

asyncChoose Computational Expression

A simple computational expression to deal with asynchronous calls that return a choice type to signal failure. Useful for calling remote services that may fail - you can call the remote service with functions of type "request -> Async>" and then chain the results together.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
71: 
72: 
73: 
module AsyncEither

type AsyncEither<'a, 'b> =
    Async<Choice<'a, 'b>>

let inline bind (m : AsyncEither<'a, 'b>) (f : 'a -> AsyncEither<'c, 'b>) : AsyncEither<'c, 'b> =
    async {
        let! c = m
        match c with
        | Choice1Of2 data ->
            return! f data
        | Choice2Of2 error ->
            return Choice2Of2 error
    }

let returnM m : AsyncEither<'a, 'b> =
    async { return Choice1Of2 m }

type AsyncEitherBuilder () =
    member x.Return m = returnM m
    member x.Bind (m, f) = bind m f
    member x.ReturnFrom m = m

let asyncChoose = AsyncEitherBuilder()

// example

let remoteCall request =
    async {
        do! Async.Sleep 100                
        return Choice1Of2 request
    }

let failedCall request =
    async {
        do! Async.Sleep 100
        return Choice2Of2 (exn ("I failed! :( - " + request))
    }

let chainedSuccess message =
    asyncChoose {
        let! firstCall = remoteCall message
        let! secondCall = remoteCall (firstCall + " second")
        
        return secondCall }
    |> Async.RunSynchronously
    |> function
       | Choice1Of2 response ->
            sprintf "Yay, I worked: %s" response
       | Choice2Of2 e ->
            sprintf "Boo, a failure: %A" e

//> chainedSuccess "hello world";;
//> val it : string = "Yay, I worked: hello world second"

let withFail message =
    asyncChoose {
        let! failure = failedCall message
        let! firstCall = remoteCall failure
        let! secondCall = remoteCall (firstCall + " second")
        
        return secondCall }
    |> Async.RunSynchronously
    |> function
       | Choice1Of2 response ->
            sprintf "Yay, I worked: %s" response
       | Choice2Of2 e ->
            sprintf "Boo, a failure: %A" e

//> withFail "hello world";;
//> val it : string =
//  "Boo, a failure: System.Exception: I failed! :( - hello world"
// The second two remote calls are never made.
module AsyncEither
type AsyncEither<'a,'b> = Async<Choice<'a,'b>>

Full name: AsyncEither.AsyncEither<_,_>
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
Multiple items
type Choice<'T1,'T2> =
  | Choice1Of2 of 'T1
  | Choice2Of2 of 'T2

Full name: Microsoft.FSharp.Core.Choice<_,_>

--------------------
type Choice<'T1,'T2,'T3> =
  | Choice1Of3 of 'T1
  | Choice2Of3 of 'T2
  | Choice3Of3 of 'T3

Full name: Microsoft.FSharp.Core.Choice<_,_,_>

--------------------
type Choice<'T1,'T2,'T3,'T4> =
  | Choice1Of4 of 'T1
  | Choice2Of4 of 'T2
  | Choice3Of4 of 'T3
  | Choice4Of4 of 'T4

Full name: Microsoft.FSharp.Core.Choice<_,_,_,_>

--------------------
type Choice<'T1,'T2,'T3,'T4,'T5> =
  | Choice1Of5 of 'T1
  | Choice2Of5 of 'T2
  | Choice3Of5 of 'T3
  | Choice4Of5 of 'T4
  | Choice5Of5 of 'T5

Full name: Microsoft.FSharp.Core.Choice<_,_,_,_,_>

--------------------
type Choice<'T1,'T2,'T3,'T4,'T5,'T6> =
  | Choice1Of6 of 'T1
  | Choice2Of6 of 'T2
  | Choice3Of6 of 'T3
  | Choice4Of6 of 'T4
  | Choice5Of6 of 'T5
  | Choice6Of6 of 'T6

Full name: Microsoft.FSharp.Core.Choice<_,_,_,_,_,_>

--------------------
type Choice<'T1,'T2,'T3,'T4,'T5,'T6,'T7> =
  | Choice1Of7 of 'T1
  | Choice2Of7 of 'T2
  | Choice3Of7 of 'T3
  | Choice4Of7 of 'T4
  | Choice5Of7 of 'T5
  | Choice6Of7 of 'T6
  | Choice7Of7 of 'T7

Full name: Microsoft.FSharp.Core.Choice<_,_,_,_,_,_,_>
val bind : m:AsyncEither<'a,'b> -> f:('a -> AsyncEither<'c,'b>) -> AsyncEither<'c,'b>

Full name: AsyncEither.bind
val m : AsyncEither<'a,'b>
val f : ('a -> AsyncEither<'c,'b>)
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val c : Choice<'a,'b>
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
val data : 'a
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
val error : 'b
val returnM : m:'a -> AsyncEither<'a,'b>

Full name: AsyncEither.returnM
val m : 'a
Multiple items
type AsyncEitherBuilder =
  new : unit -> AsyncEitherBuilder
  member Bind : m:AsyncEither<'b,'c> * f:('b -> AsyncEither<'d,'c>) -> AsyncEither<'d,'c>
  member Return : m:'e -> AsyncEither<'e,'f>
  member ReturnFrom : m:'a -> 'a

Full name: AsyncEither.AsyncEitherBuilder

--------------------
new : unit -> AsyncEitherBuilder
val x : AsyncEitherBuilder
member AsyncEitherBuilder.Return : m:'e -> AsyncEither<'e,'f>

Full name: AsyncEither.AsyncEitherBuilder.Return
val m : 'e
member AsyncEitherBuilder.Bind : m:AsyncEither<'b,'c> * f:('b -> AsyncEither<'d,'c>) -> AsyncEither<'d,'c>

Full name: AsyncEither.AsyncEitherBuilder.Bind
val m : AsyncEither<'b,'c>
val f : ('b -> AsyncEither<'d,'c>)
member AsyncEitherBuilder.ReturnFrom : m:'a -> 'a

Full name: AsyncEither.AsyncEitherBuilder.ReturnFrom
val asyncChoose : AsyncEitherBuilder

Full name: AsyncEither.asyncChoose
val remoteCall : request:'a -> Async<Choice<'a,'b>>

Full name: AsyncEither.remoteCall
val request : 'a
static member Async.Sleep : millisecondsDueTime:int -> Async<unit>
val failedCall : request:string -> Async<Choice<'a,System.Exception>>

Full name: AsyncEither.failedCall
val request : string
type exn = System.Exception

Full name: Microsoft.FSharp.Core.exn
val chainedSuccess : message:string -> string

Full name: AsyncEither.chainedSuccess
val message : string
val firstCall : string
val secondCall : string
static member Async.RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:System.Threading.CancellationToken -> 'T
val response : string
val sprintf : format:Printf.StringFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
val e : obj
val withFail : message:string -> string

Full name: AsyncEither.withFail
val failure : string
val e : System.Exception
Raw view Test code New version

More information

Link:http://fssnip.net/lV
Posted:10 years ago
Author:mavnn
Tags: computation builder , async , choice