Functional Programming – Concurrency and State Management

concurrencyfunctional programmingstate

FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state. I don't get it.

Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures. We generate a dungeon composed of rooms, corridors, heroes, monsters and loot. Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes. Our hero kills a rat, picks up a shortsword, etc.

To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this. As our hero takes action, functions amend the state of the world. It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present. Where would we allow for concurrency? We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state. It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.

Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).

I'm failing to see how concurrency is useful in my example and that may be the issue. I may be misrepresenting the claim somehow.

Can someone better represent this claim?

Best Answer

I'll try to hint on the answer. This is not an answer, only an introductory illustration. @jk's answer points to the real thing, zippers.

Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree.

But most of the new tree is exactly the same as old tree. A clever implementation would reuse most of the tree fragments, routing pointers around the altered node:

From Wikipedia

Okasaki's book is full of examples like this.

So I suppose you could reasonably alter small parts of your game world each move (pick up a coin), and only actually change small parts of your world data structure (the cell where the coin was picked up). Parts that only belong to past states will be garbage-collected in time.

This probably takes some consideration in designing the data game world structure in an appropriate way. Unfortunately, I'm no expert in these matters. Definitely it must be something else than a NxM matrix one would use as a mutable data structure. Probably it should consist of smaller pieces (corridors? individual cells?) that point to each other, as tree nodes do.