LAgent : an agent framework in F# – Part II – Agents and control messages - Luca Bolognese

LAgent : an agent framework in F# – Part II – Agents and control messages

Luca -

☕ 2 min. read

Download frame­work here.

All posts are here:

Agents

Agents are en­ti­ties that process mes­sages and keep state be­tween one mes­sage and the next. As such they need to be ini­tial­ized with a lambda that takes a mes­sage and a state and re­turns a new state. In F# pseudo code: msg –> state –> new­State. For ex­am­ple the fol­low­ing:

let counter = spawnAgent (fun msg state -> state + msg) 0

This is a counter that starts from 0 and gets in­cre­mented by the value of the re­ceived mes­sage. Let’s make it print some­thing when it re­ceives a mes­sage:

let counter1 = spawnAgent
(fun msg state -> printfn "From %i to %i" state (state + msg); state + msg) 0 counter1 <-- 3 counter1 <-- 4

Which pro­duces:

**From 0 to 3

From 3 to 7**

There is no spawn­Par­al­le­lA­gent, be­cause I could­n’t fig­ure out its us­age pat­terns. Maybe I don’t have enough cre­ativ­ity. Obviously msg and state could be of what­ever type (in real ap­pli­ca­tion they end up be­ing tu­ples more of­ten than not).

Control mes­sages

You can do things to agents. I’m al­ways adding to them but at this stage they are:

type Command =
| Restart
| Stop
| SetManager of AsyncAgent
| SetName of string

Plus some oth­ers. I’ll de­scribe most of them later on, right now I want to talk about Restart and Stop. You use the for­mer like this:

counter1 <-- Restart
counter1 <-- 3

Which pro­duces:

From 0 to 3

This should be some­how sur­pris­ing to you. You would have thought that you could just post in­te­gers to a counter. This is not the case. You can post what­ever ob­ject. This is use­ful be­cause it al­lows to have a com­mon model for pass­ing all sort of mes­sages, it al­lows for the agent not to be pa­ra­me­ter­ized by the type of the mes­sage (and of state) so that you can store them in data struc­tures and al­lows ad­vanced sce­nar­ios (i.e. hot swap­ping of code).

This is a de­bat­able de­ci­sion. I tried to get the best of strongly typ­ing and dy­namic typ­ing, while keep­ing sim­plic­ity of us­age. The im­ple­men­ta­tion of this is kind of a mess though. We’ll get there.

BTW: you use Stop just by post­ing Stop, which stops the agent (forever).

3 Comments

Comments

DotNetShoutout

2009-06-07T02:36:05Z

Thank you for submitting this cool story - Trackback from DotNetShoutout

Good mini-series. I have a some code and binaries at http://fspread.codeplex.com that shows f# agents operating in a distributed environment using the Spread Toolkit. The server models are similar to yours and also show load-balancing, fault-tolerance and leader-election.

Where can I download your library?

0 Webmentions

These are webmentions via the IndieWeb and webmention.io.