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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With