If I've got an async parameterless workflow in F#, is it necessary and/or idiomatic to make that a function, or is it best left as a raw value?
For example if I want to define getRemoteCounterAfterOneSec, polls some remote counter source, should it be
let getRemoteCounterAfterOneSec =
async {
do! Async.Sleep 1000
return! ...
}
or
let getRemoteCounterAfterOneSec () =
async {
do! Async.Sleep 1000
return! ...
}
It seems like they should do the same thing, just the latter has an unnecessary parameter. However I've seen this done both ways in various code. I've also seen places where the behavior ends up different: if using a MailboxProcessor and doing
let myFunc = mailboxProc.PostAndAsyncReply(fun reply -> GetCount reply)
async {
let! count1 = myFunc
let! count2 = myFunc
}
then the mailboxProcessor is only called once; the second time it merely returns the same value calculated in the previous call. However if myFunc is a function then it calls mailboxProcessor twice as you'd expect.
let myFunc() = mailboxProc.PostAndAsyncReply(fun reply -> GetCount reply)
async {
let! count1 = myFunc()
let! count2 = myFunc()
}
Is that a bug in the implementation? What's going on here and what is idiomatic?
When it comes to ordinary asyncs that you define yourself, then adding () has no effect (well, it means that the async that describes a computation is constructed repeatedly, but it has no practical effect).
I sometimes write it just to make my code easier to understand, or when the async is recursive (because then you get a warning when you have a recursive value). So, the following is fine, but it gives you a warning:
let rec loop =
async {
do! Async.Sleep 1000
if 1 > 2 then return 1
else return! loop }
The PostAndAsyncReply method is written a bit differently - and the name tries to reflect that. Normal F# async methods are named AsyncFooBar. This one has PostAndAsyncFooBar to indicate that it first posts and then asynchronously waits, that is something like:
let PostAndAsyncWait () =
post(message)
async { let! sth = wait ()
return sth }
So, here it actually posts outside of the async - this lets you call the function even if you are (syntactically) outside of an async block. And the name tries to be very explicit about this.
(But I would personally prefer if it was all inside async i.e. AsyncPostAndWait).
Related
Here is a client side Fable.Remoting example that prints the result of an async function.
// Client code (Compiled to Javascript using Fable)
// ============
open Fable.Remoting.Client
let server = Proxy.create<IServer>
async {
let! length = server.getLength “hello”
do printfn “%d” length // 5
}
|> Async.StartImmediate
How do I get the length value?
I see you've tagged your question with elmish, so I'm going to assume you have a Msg type defined. Don't use Async.StartImmediate or Async.RunSynchronously; in Elmish, you should use Cmd.OfAsync to schedule a message to be dispatched once the async block returns a value. There are four functions in Cmd.OfAsync (and the same four appear in Cmd.OfPromise as well): either, perform, attempt, and result. I'll break them down for you since their documentation isn't quite up to snuff yet:
either: takes four parameters, task, arg, ofSuccess, and ofError. task is the async function you want to call (of type 'a -> Async<'b>). arg is the parameter of type 'a that you want to pass to the task function. ofSuccess is a function of type 'b -> 'Msg: it will receive the result of the async function and is supposed to create a message, presumably one that incorporates the 'b result. Finally, ofError is a function of type exn -> 'Msg: if the task function throws an exception, then ofError will be called instead of ofSuccess, and is supposed to turn that exception into an Elmish message that your code can handle (presumably one that will log an error to the Javascript console or pop up a notification with Thoth.Toast or something like that).
perform: like either but there's no ofError parameter. Use this if your async command cannot fail (which is never the case with remote API calls, as it's always possible the network is down or your server is unresponsive), or if you just don't care about exceptions and don't mind an unhandled exception getting thrown.
attempt: like either but there's no ofSuccess parameter, so the task function's result will be ignored if it succeeds.
result: this one is completely different. It just takes a single parameter of type Async<'Msg>, i.e. you pass it an async block that is already going to produce a message.
With the code you've written, you would use Cmd.OfAsync.result if you wanted to make minimal changes to your code, but I would suggest using Cmd.OfAsync.perform instead (and upgrading it to Cmd.OfAsync.either once you have written some error-handling code). I'll show you both ways:
type Msg =
// ... rest of your messages go here
| GetLength of string
| LengthResult of int
let update msg model =
match msg with
// ... rest of your update function
| GetLength s ->
let usePerform = true
if usePerform then
model, Cmd.OfAsync.perform server.getLength s LengthResult
else
let length : Async<Msg> = async {
let! length = server.getLength s
return (LengthResult length)
}
model, Cmd.OfAsync.result length
| LengthResult len ->
// Do whatever you needed to do with the API result
printfn "Length was %d" len
model, Cmd.none
And if you were using either (which you really should do once you go to production), there would be a third message LogError of exn that would be handled like:
| LogError e ->
printfn "Error: %s" e.Message
model, Cmd.none
and the Cmd.OfAsync.perform line in the code above would become:
model, Cmd.OfAsync.either server.getLength s LengthResult LogError
That's the right way to handle async-producing functions in Elmish.
Async is one of the places where you use return in F#. So you need to return the length value. Also, Async.StartImmediate returns () (unit). Use something else, e.g. Async.RunSynchronously if you need the extracted value. Depends on what you need to achieve with it.
let length =
async {
let! length = async {return String.length "hello"}
do printfn "%d" length // 5
return length
} |> Async.RunSynchronously
length // val it : int = 5
Btw, you mention fable. So you might be able to use JS promise.
Some resources on Async in F#:
F# Async Guide from Jet
Async Programming
FSharp for Fun and Profit
Microsoft Docs
C# and F# Async
For those who want to call from js code.
// Client code (Compiled to Javascript using Fable)
// ============
open Fable.Remoting.Client
open Fable.Core // required for Async.StartAsPromise
let server = Proxy.create<IServer>
let len_from_fable () =
async {
let! length = server.getLength “hello”
return length
} |> Async.StartAsPromise
call from js
async func() {
let len = await len_from_fable()
print(len)
}
works in fable 3.0.
How do I await an async method in F#?
I have the following code:
type LegoExample() =
let brick = Brick(BluetoothCommunication("COM3"))
let! result = brick.ConnectAsync();
Error:
Unexpected binder keyword in member definition
Note, I reviewed the following link:
However, I only observe the functional technique and not the OOP technique.
you get the error because the let! construct (just like the do!) needs to be placed inside a computational workflow (like async { ...} but there are others - it's basically the syntactic sugar F# gives you for monads - in C# it would be the from ... select ... stuff LINQ came with and in Haskell it would be do ... blocks)
so assuming brick.ConnectAsync() will return indeed some Async<...> then you can wait for it using Async.RunSynchronously like this:
let brick = Brick(BluetoothCommunication("COM3"))
let result = brick.ConnectAsync() |> RunSynchronously
sadly a quick browser search on the page you linked did not find ConnectAsync so I cannot tell you exactly what the indent of the snippet was here but most likely you wanted to have this inside a async { ... } block like this:
let myAsyncComputation =
async {
let brick = Brick(BluetoothCommunication "COM3")
let! result = brick.ConnectAsync()
// do something with result ...
}
(note that I remove some unnecessary parentheses etc.)
and then you could use this myAsyncComputation
inside yet another async { .. } workflow
with Async.RunSynchronously to run and await it
with Async.Start to run it in background (your block needs to have type Async<unit> for this
with Async.StartAsTask to start and get a Task<...> out of it
...
Suppose I have a stream which only allows one request/response at a time but is used in several threads.
Requests/commands should be throttled such that a new request can only occur once
the previous request has been sent and a reply has been received.
The user would be able to do this
let! res = getResponse("longResp")
let! res2 = getResponse("shortResp")
and not really know or care about the throttle.
I have tried with a modified version of Tomas Petricek's Throttling Agent that allows async with return values, but this requires the user to call getResponse("..") |> Enqueue |> w.Post which is a recipe for disaster (in case they forget to do so).
Is there a good/idiomatic way of doing this in F#?
Then make it explicit in your type system that the returned type needs to be unwrapped with another function. So instead of returning an Async<'T> which as you pointed out can be called directly with Async.Start, rather return something like:
type Queuable<'T> = Queuable of Async<'T>
Then getResponse changes to return a Queueable:
let getResponse (s:string) =
let r =
async{
do! write to your stream
return! read from your stream
}
Queuable r
Provide a function that unwraps the Queuable:
let enqueue (Queuable q) = async{
return! processor.PostAndAsyncReply(fun replyChannel -> replyChannel,q)
}
The processor is an agent that simply runs the Async workflow. Something like this:
let processor = new MailboxProcessor<_>(fun inbox ->
let rec Loop() = async {
let! (r:AsyncReplyChannel<_>,job) = inbox.Receive()
let! res = job
r.Reply res
return! Loop()}
Loop())
It looks like if the following situation occurs often and I wonder
What would be the most appropriate and shortest F# equivalent (e.g. no extra tasks created, has the same SynchronizationContext etc.)?
Does the following have something that should be fixed or improved?
Here DoAsync is a member function derived from a framework class, it takes a parameter and returns a hot, awaited task to the caller that is some framework function.
In C#:
public async Task DoAsync(int x)
{
if(x == 10)
{
await taskContext.ReturnAsync();
}
}
Here Async.Ignore is from here
In F#:
member x.DoAsync(int x) =
async {
if x = 10
return! Async.AwaitTask(taskContext.ReturnAsync() |> Async.Ignore)
else
return! Async.AwaitTask(Task.FromResult(0))
} |> Async.StartAsTask :> Task
Look at Tomas' answer for a simpler way. As an added note, in F# 4.0 it looks like there's an overload for non-generic Task available. More details at this Visual F# Tools PR.
Using Async.AwaitTask and Async.StartAsTask is the way to go. Although you do not really need to return anything from the async if you just want to return a non-generic Task:
member x.DoAsync(x:int) =
let work = async {
if x = 10 then
do! taskContext.ReturnAsync() |> Async.Ignore }
Async.StartAsTask(work) :> Task
My understanding is that what a workflow builder does is that it first "builds" the expression, and then subsequently executes it. So given that it first builds the expression, it should be able to count the number of let! statements before actually executing, right? And then it should be able to inject some logging that monitors progress? So is it possible to rework the async builder to automatically report progress and kill the printfn redundancy below?
async {
let! a = doSomething1 ()
printfn "%d/%d" 1 4
let! b = doSomething2 a
printfn "%d/%d" 2 4
let! c = doSomething3 b
printfn "%d/%d" 3 4
let! d = doSomething4 c
printfn "%d/%d" 4 4
return d
}
For loops, I guess just assume that the whole loop is a single step. Only top-level expressions count as steps here.
(Note if there's a way to do this without making a whole new workflow builder I guess that's fine too).
Note I've already gone through the path of a) making a "Task" iterator that just iterates tasks (but then you lose e.g. use handling, so it ended up being inadequate), and b) making a task counter, but that always had to be seeded and iterated manually so I'm hoping for something better.
As you tagged the question with the tag monads, I'll start by a theoretical nitpick. What you want to do would not actually be a monad. The problem is that monads require certain laws (see the Haskell page on monads). For F#, this means that the following two snippets should mean the same thing:
let computation1 =
async { let! x = m
return x }
let computation2 = m
This would not be the case for the extension you suggest, because computation1 has one more let! than computation2. Now, I do not think this is actually a problem - the logging could still be useful (even if it may give different results than you'd expect in some cases).
Adding this feature to F# async is not as easy - the problem is that you'd need to define your own type that replaces (or wraps) standard Async<'T>. The type needs to store the number of steps. If you can store the number of steps somewhere else (e.g. some mutable counter), then you just need to redefine the computation builder for async.
Here is a minimal example that does something like this - it just prints "step" for each let!:
// A custom computation builder that redirects all operations to
// the standard 'async' builder, but prints "step" in the Bind method
type LogAsyncBuilder() =
member x.Bind(c1, f) = async {
let! arg = c1
printfn "step!"
return! f arg }
member x.Return(v) = async.Return(v)
member x.ReturnFrom(c) = async.ReturnFrom(c)
// An instance of our custom computation builder
let logAsync = LogAsyncBuilder()
// Example that prints 'step' 4 times (for every Bind - let!)
let doSomething n = logAsync {
return n + 10 }
logAsync {
let! a = doSomething 0
let! b = doSomething a
let! c = doSomething b
let! d = doSomething c
return d }
|> Async.RunSynchronously
You could use a tuple ('a, int, int) to track the current result, the total number of steps and the number executed so far. Then you could write a function to take the current state, and the next async function to execute e.g.
//create the initial state
let startCount steps = ((), 0, steps)
let withCount af (a, c, steps) = async {
let nc = c + 1
let! res = af a
do printfn "%d %d" nc steps
return (res, nc, steps)
}
withCount takes a function which returns the next async operation, and the current state. It creates the next workflow, increments the number of executed steps and prints the status before returning the new state.
You can then use it like:
async {
let init = startCount 4
let! t = withCount doSomething init
let! t2 = withCount doSomething2 t
let! (r, _, _) = withCount doSomething3 t2
return r
}