Tag Archives: F#

Bind? No.. Apply…? No… Map!?

After continuing my foray into the functional with Giraffe and .NET Core, I have struggled with the code not quite reading very well. Various data sources are pluggable, i.e. they can be replaced with mocks if you don’t want to run other supporting systems while debugging. This pluggability along with the way Giraffe handles some of its configuration means that – while we would like to compose partially applied functions with either mocked or actual services baked in that are then passed in to the relevant handlers, we instead have to pass a HttpContext around everywhere. If you followed that link you probably wondered why we did not just use the strategy outlined in that blog series. I can only say that we did not understand fish operators at this point. 

So we turn to the googles, and as usual the first or second hit lands us on F# for fun and profit. Scott Wlaschin introduces us to the Reader Monad. We watch his talks, we read his blog posts. A week of enthusiastic coding goes by.

Essentially – the reader monad allows you to write and construct all the code and only at the end plug in the HttpContext as the whole thing is evaluated and returned to the caller.

You make a Reader<‘env, ‘data>  and you create functions to wrap and unwrap things in and out of the Reader. Then you make functions that mind their own business but they return Reader<‘env, b: and you allow the reader to handle some railway oriented programming for you. Essentially you lay the track all through the code but on the last line in the handler you put the train on the tracks and set it off, only then realising whether or not it ended up running through the failure cases or went all through the success track.

Wrappers, essentially, like Option<‘a>, IEnumerable<‘a> or Reader as described above, are introduced as Elevated things. The proper word seems to be Monadic types, but that does not seem to be a good term, as there is no need for a wrapper type to be a monad, although they can be. After a few specific examples the general case is presented and it turns out you can do a bunch of stuff with these elevated types only using functions like bind, return, apply and map. There is a brief epiphany as we experience a flicker of understanding of  the monad laws.

A monad is just a monoid in the category of endofunctors, what is the problem?

Now I cannot explain the chaining of elevated and non-elevated functions properly. I know what bind does, and I can use it correctly on the first try. Return is obvious. Map and apply though… it’s like being ten years old again and round-robining commands until the compiler is happy. As it stands all I can do is link to the posts we have read and the metaphors that have been presented to me, that I have half understood and then tried to reconcile with other conflicting metaphors.

Inevitably the golden success case of “first I need this, then I pass it to this other thing and then I flip it, kick it and reverse it and then I return it” is soon replaced by “well, first I need this one thing, that I need to just check against this other thing, but then use it again in this third thing which I convert to this fourth thing that I might return if this fifth thing is true” and the nice chaining goes out the window and it makes you sad.  Every let b =  … feels like a let-down (hence the name).

This let = thing is apparently called applicative style, where you compose values, while chaining is called monadic style. At least it has name. 

So after a while when you have been writing things like

task {
    let! a = coolFunc b c
    return! a |> modifyInAnAwesomeWay
}
async {
   let! a = thingThatDoesDatabaseThings b 
   return! match a with 
      | Some data -> coolThing data
      | None -> unCoolError
}

You start wondering what the heck it is you are doing. What are these things? It turns out they are computational expressions. But how do I make them?  You essentially create a ThingBuilder class with members for bind and return, and then create a let thing = new ThingBuilder(), after which you can write expressions like:

thing {
    let! unwrapped = funcThatGetsPassedToBind arg
    return unwrapped
}

To be a bit enterprisey I have come up with a draft of a brilliant thing. The F# Functional Maturity Model (FFMM):

  1. Can get samples to compile even with modifications
  2. Can get write small programs that do useful things in prod
  3. Can write software systems that fulfill a business purpose
  4. Can see how bad OO in F# looks and strive to create functional style code
  5. Attempt to write a monad tutorial
  6. See the beauty of computational expressions and want to use them everywhere
  7. Stops being afraid and starts to love Kliesli composition (the fish operator)
  8. Realise computational expressions are an antipattern and curse their existence
  9. ..

 As you can see I have yet to ascend the ladder enough to know what all the levels are, but I am currently on 6 I believe, but given the hate people have for do in Haskell, it seems that there must be a level where you realise the computational expressions are of the devil and must be eliminated at all cost, but at the level where I am now, they do indeed seem like they cut away a lot of plumbing code where I otherwise map and bind to call various things. Also, I see the fish operator everywhere so clearly it must be awesome. I now at least understand what it does, but I can’t say it fits very well in the code I want to write. I’m sure that is an epiphany for a later date. 

Advertisements

The Actor Model

In the .NET community perhaps the Actor model of computing is not all that familiar. In this post I will briefly describe my understanding of the possibilities it gives the “real life” Enterprise LOB-application developer without going into specifics.


Different abstraction

The Actor model is a different abstraction from the normally more machine-like multithreaded server process model. This model sees the software system as a set of Actors listening for incoming messages. Messages are sent using to mailing addresses, conceptually, as in – not a hard reference to a running piece of code of any kind. An actor can only send messages to other actors that it knows the address of. It will know only of actors it receives messages from or creates itself. Unintuitively, the communication between actors is handled through a concept known as Channels, which would imply something more direct than a mail-drop system. In common implementations today, channels are implemented as queues.

The Actor will react to the incoming message by either sending a finite number of messages, creating a finite number of actors as well as deciding how to handle the next incoming message. The messages contain all the information needed for this processing, so there is no global state to modify or any shared resources to wait for. Each actor has its own execution context. Whether you execute all actors in the same thread in the same process or whether you have tens of thousands of separate machines with a multitude of threads of execution in several processes does not matter to the actor. This leads to a fantastic potential for scalability as there is little or no negative coupling.

Real-world examples?

If you think about it more closely, the Actor model can be said to better model the organizations we are building systems for. If a process requires a certain number of steps to be taken, modelling the steps, or actually the coworkers performing the step, as actors and the piece of paper or file that would travel from desk to desk can be modelled as a message. Just like faceless corporate drones, actors can be stateful, as is evident from the definition above.

In the Actor model data is not encapsulated but rather transmitted as messages between actors that perform actions with that data and then send the information forward. In object oriented programming you still send messages, conceptually, but actually you call methods on the object, but the objects are one with their data and the only way to modify the data is by sending a message to the object and hope the object will allow itself to be modified in the way you want.

There are large practical similarities between classic object oriented programming and the Actor model, and the Actor model frameworks implement actors as “objects” and use the OOP toolbox to implement the infrastructure that the frameworks provide, but the conceptual differences are importan remember when working with this model.

What frameworks exist for .NET?

There are two well known Actor model framework for .NET, Retlang (http://code.google.com/p/retlang/) and Stact. They both provide the basics you can expect from a framework of this kind, only Retlang stray somewhat from the Actor model nomenclature and provide no remote messaging capability, focusing on high performance in-memory messaging. It is unclear how development proceeds with Retlang, but there is support for .NET 4.

Another framework that supports Actor model is Stact https://github.com/phatboyg/Stact) which uses concepts more closely linked to the specification and would be preferable by those who like conceptual clarity.

Recently, F# has introduced the concept of F# Agents, which is essentially actors. They have isolation between instances (actors) and respond asynchronously to incoming statically typed messages.  (http://www.developerfusion.com/article/139804/an-introduction-to-f-agents/)

We will proceed and show a brief example using F# as it is less verbose than other ways of implementing this architecture. The examples are slightly modified from the above link and also ripped straight from the horse’s mouth, i e  Don Syme’s post http://blogs.msdn.com/b/dsyme/archive/2010/02/15/async-and-parallel-design-patterns-in-f-part-3-agents.aspx 

open Microsoft.FSharp.Control
type
Agent<‘T> = MailboxProcessor<‘T>

let agent =
    Agent.Start(
fun inbox ->
        let rec loop n = async
{
           
let!
msg = inbox.Receive()
            printfn
“now seen a total of %d messages”
(n+1)
           
return!
loop (n+1)
        }
        loop 0 )

for i in 1 .. 1000 do
    agent.Post (sprintf “Hello %d” i )

The above agent uses a builtin class called MailboxProcessor that allows you to post messages, passing in the actual Processor function as an argument, “putting the fun back into functional”.

Of course this is a silly example that doesn’t make anybody happy. Let’ s show something more network-related, so that you can imagine the implications.

open System.Net.Sockets

 

/// serve up a stream of quotes

let serveQuoteStream (client: TcpClient) = async {

    let stream = client.GetStream()

    while true do

        do! stream.AsyncWrite( “MSFT 10.38″B )

        do! Async.Sleep 1000.0 // sleep one second

}

 

What is the point of this then? Well, the agents are asynchronous and take no resources while waiting.  You might as well create a bunch of actors that will all lie there waiting for an incoming request and deal with them asynchronously with mindblowing efficiency. Every Actor (or instance of Agent) has its own state completely isolated from the others. See? No problems with shared mutable state. Put the foot on the accelerator and press it all the way to the floor.

Error management in Actors

Below is an example of error management using a supervisor that will take care of your vast pool of actors and deal with their failures. Again, contrived example, but remember you have all of the .NET framework at your disposal, so just imagine the supervisor doing some really clever reporting or cleanup.

open Microsoft.FSharp.Control

type Agent<'T> = MailboxProcessor<'T>

module Agent = 
   let reportErrorsTo (supervisor: Agent<exn>) (agent: Agent<_>) = 
       agent.Error.Add(fun error -> supervisor.Post error); agent

   let start (agent: Agent<_>) = agent.Start(); agent

let supervisor = 
   Agent<int * System.Exception>.Start(fun inbox ->
     async { while true do 
               let! (agentId, err) = inbox.Receive()
               printfn "an error '%s' occurred in agent %d" err.Message agentId })


let agents = 
   [ for agentId in 0 .. 10000 ->
        let agent = 
            new Agent<string> (fun inbox ->
               async { 
                    while true do 
                        let! msg = inbox.Receive()
                        if msg.Contains("agent 99") then 
                            failwith "I don't like that cookie!" }
                ) 
        agent.Error.Add(fun error -> supervisor.Post (agentId, error))
        agent.Start()
        (agentId, agent) ]

for (agentId, agent) in agents do 
   agent.Post (sprintf "message to agent %d" agentId )


Conclusion

The implications that arise from the Actor model and F# Agents in particular is that where you can use messaging (you are free to use F# Type Providers to make your various XML WebService packets become F# Types) you can process them with great efficiency to trigger all sorts of  .NET functionality asynchronously. You could use F# Agents to back your WebApi services to make the code more concise and responsive. There is no end to the possibilities.

For further reading, please don’t hesitate to follow Don Syme at http://blogs.msdn.com/b/dsyme/  and the various blogs and documentation available through there.