Skip to content

Instantly share code, notes, and snippets.

@vkobel
Created April 24, 2014 15:30
Show Gist options
  • Save vkobel/11258921 to your computer and use it in GitHub Desktop.
Save vkobel/11258921 to your computer and use it in GitHub Desktop.
Simple F# agents (MailboxProcessor) example. Try it here: http://www.tryfsharp.org/create/vkobel/Agent.fsx
type CounterMessage =
| Update of float
| Reset
let inbox = MailboxProcessor.Start(fun agent ->
// Function that implements the body of the agent
let rec loop sum count = async {
// Asynchronously wait for the next message
let! msg = agent.Receive()
match msg with
| Reset ->
// Restart loop with initial values
return! loop 0.0 0.0
| Update value ->
// Update the state and print the statistics
let sum, count = sum + value, count + 1.0
printfn "Average: %f" (sum / count)
// Wait before handling the next message
do! Async.Sleep(1000)
return! loop sum count
}
// Start the body with initial values
loop 0.0 0.0
)
inbox.Post(Update 10.0)
inbox.Post(Update 5.0)
inbox.Post(Reset)
inbox.Post(Update 2.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment