I am translating all my f# code to use async. I am finding it more difficult than expected, and I would like to know if there is a better way or I am missing something.
Take these two functions:
let test1() =
let y =
let x =
let z = f()
5 + z
x + 6
y + 3
let test2() =
let z = f ()
let x = 5 + z
let y = x + 6
y + 3
These functions are completely equivalent, but my code happens to be in the style of test1.
It seems that code written like test1 is very costly to translate to async. For example, suppose function f () becomes async:
let f () =
async{
return 3
}
The question is how to translate test1 and test2. It turns out that test2 is rather easy to fix:
let test2Async() =
async{
let! z = f ()
let x = 5 + z
let y = x + 6
return y + 3
}
you just need to type one "async {}" , one "!" and one "return".
But if you do the same with test1, it will not compile:
let test1AsyncWrong() =
async{
let y =
let x =
let! z = f() // ERROR HERE: we are not in a computation expression, so I can't use !
5 + z
x + 6
return y + 3
}
Here is, as far as I know, what you really need to do to properly translate test1:
let test1AsyncRight() =
async{
let! y =
async{
let! x =
async{
let! z = f()
return 5 + z
}
return x + 6
}
return y + 3
}
Notice that I needed to type async{} three times, plus "!" three times and "return" three times.
This seems like an unnecessary and counterintuitive complication. It feels like there is something wrong. Translating code like that will take days if I have to do this.
Am I missing something? What's going on? Thanks for any help.