Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Using Return Values From Async

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
like image 529
Chico Avatar asked Sep 13 '16 09:09

Chico


1 Answers

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
like image 142
TheQuickBrownFox Avatar answered Sep 22 '22 07:09

TheQuickBrownFox