I want to know how to deal when you have some states in a program, with functions that depends on them, but with a immutable approach. I read some examples and questions, but all focus in a small scenario, I want to understand this in a bigger program, close to real world.

My question isn't about some programming language or paradigm (it could be done with Java for eg. since we don't change variables values), so I'll illustrate a simple problem with this pseudo code:

--some states of my program
playerOne = {
  cards :: [Card]
  score :: Int
playerTwo = {
  cards :: [Card]
  score :: Int
tableCards :: [Card]

--a function that will perform a move in a game
--it needs to move a card from player to tableCards
--it needs to change the other player score with -1

showScore() --p1: 10 p2: 9 tableCards: 1
showScore() --p1: 9 p2: 9 tableCards: 2
showScore() --p1: 9 p2: 8 tableCards: 3
showScore() --p1: 8 p2: 8 tableCards: 4

First: in "doSomeMove()" I need to read a player cards. Since I'll call this function in the middle of the game I can't read from "playerOne" variable, since it's immutable and won't change in the middle of the game! So how can I solve this? To read actual program current states? do I need to always receive the actual player cards states by parameter?

Second: I'll change cards (both player and table) and other player score in this function. As I can't really change the variables (since it's immutable) I'll clone them, and set the changed state in a local variable inside the function, right? But how can next function (doSomeMove() or others) will know about this change?

Basically, the only thing that I can think to solve is: getting whole program state by parameter, do some changes, and return everything as parameter as well to next function use and be aware of state changes. But I think this is very unpractical, since if I have 20 states, and 50 functions, do I need to all 50 functions passing and return all 20 states each one?

I don't want to solve this problem, just to understand how to solve programs like this or bigger with immutability. And I hope this question helps another people, since I asked to some people how to solve this and no one answered surely! Thanks!

closed as unclear what you're asking by user22815, user40980, user53019, Ixrec, Arseni Mourzenko May 4 '15 at 16:35

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    I am not sure you understand what immutability means. You can read immutable state quite easily, in fact it has many benefits because reads are consistent due to it not changing. What is it exactly you are trying to achieve? I also recommend reading up on existing questions about immutability. – user22815 Apr 29 '15 at 3:39
  • 2
    @Snowman It's oddly phrased, but I'm pretty sure what he means is that since playerOne is immutable, it won't have the current state - so how can state be updated? – Izkata Apr 29 '15 at 4:56
  • 1
    @Izkata The immutable still has state. And no, you don't change it - you create a new one (what '20 states' means is... confused, an object has one composite state). That is the pattern with immutable objects. But as written, it seems that... well... its very confused. – user40980 Apr 29 '15 at 13:03
  • @Snowman , Izkata said exactly what I want. MichalT, I undestand that you need to create a new one object, but if I have 20 players (20 states) how can I transport the info of new objects between them? I want to read the actual score value from a player in the middle of the program execution, how can I achieve that? – Wagner Apr 29 '15 at 15:04

At the topmost level, you can use a fold to feed the output of the last step into the input of the next step without having to give it an intermediate name that gets reassigned. Basically, at each step you create a whole new scope. This part is a lot easier with functional reactive programming or actors.

Below that level, the key insight is because of immutability, your state variables do not always have to stay grouped together. You can sort of deconstruct your state on the way down the stack, creating as many copies or slices as you need, then you reconstruct it on the way back up. That way the functions you create do not need to be aware of the entire state, just what gets passed in as their arguments.

Your doSomeMove example would take in a player's hand, the table cards, and the opposing player's score, and return new values for all those. It might be implemented like this:

doSomeMove(hand, table, score)
    (newHand, removedCard) = removeCard(hand)
    newTable = addCard(table, removedCard)
    return (newHand, newTable, decrementScore(score))

Then the code that calls doSomeMove would take in all the players' hands, and all their scores, deconstruct it to make the call, then reconstruct it:

callingCode(hands, scores, table)
    (playerHand, opponentHand) = hands
    (playerScore, opponentScore) = scores
    (newPlayerHand, newTable, newOpponentScore) = doSomeMove(playerHand, table, opponentScore)
    return ((newPlayerHand, opponentHand), (playerScore, newOpponentScore), newTable)

There are patterns that can simplify this, and you can split this out into multiple levels of abstraction, but my point was to show the basic approach to take such that doSomeMove doesn't need to be aware of your entire state, just what's relevant. The lower down in the call stack you go, the less state you need. For example, removeCard has no idea whose card is being removed. It takes some practice to be able to avoid passing all your state all over the place, but it is doable.

  • thank you so much! I also talked about this question with some friends of mine who know functional programming, and they appointed this (game card) is not appropriate to solve with FP/Immutability. Is this right? I was thinking that "everything" could be done with immutability even in cases that isn't the right tool for the job. I will accept as correct, but I'll appreciate some reply about this comment, thanks again Karl! – Wagner Apr 30 '15 at 0:33
  • Yes, you can do just about everything with immutability. Whether it's a good fit depends on your point of view. On one hand, it's fairly difficult to get this kind of problem right with FP, especially for a beginner, as you've discovered. On the other hand, during the process of getting it right, you're pretty much forced to arrange your data and functions in a highly decoupled way that often lends itself to some very elegant solutions. – Karl Bielefeldt Apr 30 '15 at 2:11

To reflect the changed state of an object (I will call this object now and reference with this to the OOP paradigm) you can return this object again which in itself is immutable again, e.g.

playerOne = doSomeMove(playerOne)

Basically this is the idea behind the state pattern.

With this the single object is immutable but your changes are reflected by creating new objects (which is also the way an immutable list works).

If you have to change two objects at once then you have to look how to return them.

I think your basic misconception is to use global variables and treat them as immutable (differentiate between an immutable object state and an immutable variable.

  • I'm asking about immutable variables too, as is mandatory in Haskell for eg. So I can't re-assign "playerOne". – Wagner Apr 29 '15 at 15:02
  • @Wagner If everything is immutable (objects and variables) then your system will be immutable. I cannot think of any use of an immutable system... – Uwe Plonus Apr 30 '15 at 5:28
  • what about Haskell so? – Wagner Apr 30 '15 at 16:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.