6

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
2
  • 7
    Why are you ignoring the result of Async.RunSynchronously? That function will return your two parallel results in an array, then you just add the elements together normally... Commented Sep 13, 2016 at 10:03
  • 1
    Hi - the absolute honest answer is because I don't know what I'm doing, I'm still learning F#. Using your comments, I was able to sort it so thanks - I appreciate the time. If you could post it as an answer, I can accept. Commented Sep 13, 2016 at 11:35

1 Answer 1

10

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
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.