F Sharp (programming language): Difference between revisions

Content deleted Content added
Shr2012 (talk | contribs)
Shr2012 (talk | contribs)
Agent programming: replaced the example with concurrent queue implementation with mailboxprocessor.
Line 539:
===Agent programming===
F# supports a variation of the [[Actor model|Actor]] programming model through the in-memory implementation of lightweight asynchronous agents. For example, the following code defines an agent and posts 2 messages:
 
<syntaxhighlight lang="fsharp">
type Message =
let counter =
| Enqueue of string
MailboxProcessor.Start(fun inbox ->
| Dequeue of AsyncReplyChannel<Option<string>>
let rec loop n =
 
async { do printfn "n = %d, waiting..." n
// Provides threads concurrent access to a list of strings
let! msg = inbox.Receive()
let listManager = MailboxProcessor.Start(fun inbox ->
return! loop(n+msg) }
looplet 0)rec messageLoop list = async {
let! msg = inbox.Receive()
match msg with
| Enqueue item ->
return! messageLoop (item :: list)
 
| Dequeue replyChannel ->
match list with
| [] ->
replyChannel.Reply None
return! loop(n+msg)messageLoop }list
| head :: tail ->
replyChannel.Reply (Some head)
return! messageLoop tail
}
 
// Start the loop with an empty list
messageLoop []
)
 
// Usage
async {
// Enqueue some strings
listManager.Post(Enqueue "Hello")
listManager.Post(Enqueue "World")
 
// Dequeue and process the strings
let! str = listManager.PostAndAsyncReply(Dequeue)
str |> Option.iter (printfn "Dequeued: %s")
 
}
|> Async.Start
 
 
</syntaxhighlight>