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.
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.