Clojure Style Agents in F #

I am trying to code some Clojure style agents in F # using MailboxProcessors. Here is what I still have:

namespace GameEngine type Agent<'T>(inital:'T) = let mutable state:'T = inital let queue = new MailboxProcessor<'T -> 'T>( fun inbox -> let rec loop count = async { let! msg = inbox.Receive() state <- msg(state) return! loop(count + 1) } loop 0) do queue.Start() member self.Send(action:'T -> 'T) = queue.Post(action) member self.Deref() = state 

So, the main idea is that we have a mutable state that can be updated by calling .Send (). My question is, will my messages ever fail? If msg A is dispatched before B is the asynchronous function above, always handle A to B?

It seems like such a class should already exist in F #? Am I reinventing the wheel?

+4
source share
2 answers

If msg A is sent before B is the asynchronous function above, always process A to B?

Yes. (You can see the code for the mailbox

http://fsharppowerpack.codeplex.com/SourceControl/changeset/view/54799#970072

go to the compiler \ 2.0 \ Nov2010 \ src \ fsharp \ FSharp.Core \ control.fs and, in the end, see, for example,

  member x.Post(msg) = lock syncRoot (fun () -> arrivals.Enqueue(msg); ... 

which shows that it's just a turn under lock and key.)

It seems like such a class should already exist in F #? Am I reinventing the wheel?

Well, it’s not immediately clear to me how this differs from simply modifying the volatile global variable willy-nilly (modulo atomicity of simultaneous updates, you said “earlier” in the question, so it’s not clear to you whether this aspect has a question). What is the context for this?

+2
source

There is no built-in implementation of the Clojure-style agent.

I also at some point worked on a fast and dirty F # implementation similar to yours, but I did not find the time to consider all the correctness problems; in particular, is it not true that "T can be a value type (a struct ) larger than 64 bits (or 32 bits, depending on the case), which can cause a break (I believe that Clojure, like Java, does not work for me there are structures to worry about here.) Perhaps a restriction of type F # ( 'T when 'T : not struct ) will be needed?

+1
source

Source: https://habr.com/ru/post/1337408/


All Articles