2

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
0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.