Syntax optimization for mapped asynchronous sequences in F #

I am trying to figure out the efficient syntax for the following F # expression. Let's say I have an asynchronous F # calculation:

let asyncComp n = async { return n }

He has a signature 'a -> Async<'a>. Now I define a sequence of them:

let seqOfAsyncComps = 
    seq {
        yield asyncComp 1
        yield asyncComp 2
        yield asyncComp 3
    }

Now I have an element seq<Async<int>>. What if I want to display elements from seq<Async<int>>in asynchronously seq<Async<int>>. This will not work:

let seqOfAsyncSquares =
    seqOfAsyncComps |> Seq.map (fun x -> x * x) // ERROR!!!

Of course xthere is Async<int>, I need to extract it first int, so I can do the following:

let seqOfAsyncSquares =
    seqOfAsyncComps |> Seq.map (fun x -> async { 
                                            let! y = x
                                            return y * y }) // OK

This works fine, but the syntax is awkward. It removes the compactness of F #, and if I want to link several processes seq, I have to do the same trick in each map, filteror iter.

, , .

+4
1

Async.map ( ):

module Async =
  let map f workflow = async {
    let! res = workflow
    return f res }

let seqOfAsyncSquares' =
    seqOfAsyncComps |> Seq.map (Async.map (fun x -> x * x))

, , , , :

> seqOfAsyncSquares' |> Async.Parallel |> Async.RunSynchronously;;
val it : int [] = [|1; 4; 9|]
+5

All Articles