Functional Programming – Dealing with State Problems

functional programming

I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle "objects" with a mutable position to update. How are inherently "stateful" problems typically solved using functional programming techniques?

Best Answer

Functional programs handle state very well, but require a different way of looking at it. For your position example, one thing to consider is having your position be a function of time instead of a fixed value. This works well for particles following a fixed mathematical path, but you require a different strategy for handling a change in the path, such as after a collision.

The basic strategy here is you create functions that take in a state and return the new state. So a particle simulator would be a function that takes a Set of particles as input and returns a new Set of particles after a time step. Then you just repeatedly call that function with its input set to its previous result.

Related Topic