3 ms·
Store a list of actions, and represent your state as a sum of said actions. That way, no matter what the action is, "undoing" an action is literally just poppin
by yen223 9y ago
Store a list of actions, and represent your state as a sum of said actions. That way, no matter what the action is, "undoing" an action is literally just popping it off the list.
actions = [append("The"), append(" quick"), append(" brown"), append(" fox")]
state = reduce(actions, some_combiner) // This might give you a string "The quick brown fox"
If you pop the last element `append(" fox")` of the actions and rebuild the state, you can easily see that the new state "The quick brown" is simply the old state without the last action, i.e. an "undo".
If rebuilding the state is expensive, it is not hard to devise caches around state management under this model.
- maxxxxx 9y agoMakes sense. But i don't see how this is related to OO vs FP then. Putting all your actions into a list is easy. Replaying is easy. The main problem is caching the state which can become tricky no matter OO or FP.
- yen223 9y agoYou're right in that nothing about this is specific to OO or FP. However, under this model, you really don't want your actions in the actions list to change after the fact. That means those actions in the list really shouldn't be modeled as "objects" with object-like mutable internal state and all. In fact, you'd probably need them to be as lightweight as possible, which means no sticking methods on them. With those constraints in mind, OO-style code brings nothing to the table.
- maxxxxx 9y agoI think this unfortunately goes into the same direction a lot of political discussions tend to go. Two rigid philosophies and one has to win. In the real world either one can work if applied correctly. And both can learn from each other. FP brings a lot of interesting concepts to the table that are useful. But I doubt that people that screw up OOP will screw up less with FP In the end competent and disciplined (in my view the number one attribute of a good dev) people will produce good software with any paradigm. Clueless people will cause problems no matter what the tool is.
- Tehnix 9y agoMy arguments was actually just that it had nothing to do with OO at all :) Caching becomes a lot easier though in a pure functional programming lang though, and in a lazy one happens automatically for a lot of things.