jameszhao00
jameszhao00

Reputation: 7301

F# Async Map different types

Is there some way to do the following using f#?

let expr0:Async<int> = get0...
let expr1:Async<string> = get1...
//please pretend that this compiles
let finalFuture:Async<string> = 
    Async.Map2 expr0 expr1 (fun (v0:int) (v1:string) -> v0 + v1 ) 

let final:string = Async.RunSynchronously finalFuture

Upvotes: 2

Views: 474

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

There is no pre-defined map function for asynchronous computations. Perhaps because it really depends on how you want to evaluate the two computations.

If you want to run them sequentially, you can use:

let finalFuture = async {
  let! v0 = expr0
  let! v1 = expr1
  return v0 + v1 }

If you want to run them in parallel, you can use Async.Parallel or Async.StartChild. For example:

let finalFuture = async {
  let! v0Started = Async.StartChild(expr0)
  let! v1Started = Async.StartChild(expr1)
  let! v0 = v0Started
  let! v1 = v1Started
  return v0 + v1 }

In both cases, it would be quite easy to change the code to take a function rather than calling + directly, so you should be able to use the two snippets to define your own map2 function.

Upvotes: 6

Related Questions