Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a multi-client server that doesn't have mutable state?

I am looking at functional programming and struggling with one point.. How do I do the following without mutable state?

Imagine I have a server.. and clients try to connect.. and each client gives the server a number and gets told the current total.

Now without mutable state the server can't keep a total... so I am thinking each client is really creating a new server containing a new total.. or a new server holding the entry and referencing the old server so the total can be calculated.

BUT.. how do the client's find the server? Someone has to hold onto the current server instance.. so they have a mutable variable 'server'.

No matter what I do.. I always end up with a mutable variable a the higher scope.

Thoughts?

like image 286
Nigel Thorne Avatar asked Jul 11 '10 12:07

Nigel Thorne


2 Answers

The scenario you describe could be implemented like this (pseudocode):

let keepTrackOfTotal(total) =
    let conn = waitForConnection()
    let x = readIntFrom(conn)
    let newTotal = total + x
    writeIntTo(conn, newTotal)
    keepTrackOfTotal(newTotal)

let main() = keepTrackOfTotal(0)

Here we use recursion to get an infinite loop that keeps track of the total, without mutable variables.

like image 139
sepp2k Avatar answered Nov 18 '22 09:11

sepp2k


At least in Erlang the way it's done is that the process itself has a name.

So while the server loop is constantly starting new versions of itself (by calling the same function at the end of the call, like in sepp2k's excellent pseudocode) and feeding in the sum as a parameter, all your clients are contacting that process by name, so they can still find it.

like image 45
Jon Smock Avatar answered Nov 18 '22 08:11

Jon Smock