I'm trying to learn F# but I keep running into issues. The latest is using async. In the code below, I'm trying to run two long running operations and perform a calculation based on the result but I get an error "Async does not support the + operator". I have tried casting etc to get it to work but I'm not getting anywhere fast.
Could someone please explain where I'm going wrong.
Thanks.
let SumOfOpFaults =
async{
printfn "Getting Sum of Op Faults"
return query {
for a in AlarmResult do
sumBy a.UserFaultTime
}
}
let SumOfMcFaults =
async{
printfn "Getting Sum of Machine Faults"
return query {
for a in AlarmResult do
sumBy a.MachineFaultTime
}
}
[SumOfMcFaults; SumOfOpFaults]
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
let total = SumOfOpFaults + SumOfMcFaults // <---Error Here
SumOfOpFaults
is defined as an Async<'T>
. It will never change to a 'T
so you can't use +
on it later.
Async.Parallel
turns any sequence of Async
computations into one Async
computation that runs them in parallel and returns an array.
Async.RunSynchronously
doesn't give you a result by side effects, but as a return value. So you just need to do this:
let total =
[SumOfMcFaults; SumOfOpFaults]
|> Async.Parallel
|> Async.RunSynchronously
|> Array.sum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With