jeudi 5 novembre 2020

Caching calculated values in functional languages - design problem

I'm relatively new to functional programming, as an exercise I'm trying to implement card game called 'addenda'. Problem I'm facing now is, as I think, exemplification of something more general.

To correctly implement some of the game rules I need some auxiliary data. This data can be stored in a state of the game, in my opinion polluting game model, or recalculated each time player action is made. So in my opinion this is kind of a trade off.

Now, in OO design I could implement such a component (let's name it ValueCalculator) using DI, injecting service that calculates needed value each time its needed, or simply inject some decorator that stores values in its internal cache, that is not seen from outer perspective. So I can achieve some degree of flexibility not polluting rest of the domain model, and exchange behavior without even recompiling core of the application - changes have to be made only in composition root.

Is there a way of achieving the same flexibility using purely functional constructs (I'm not counting classes, interfaces and mutable state here of course)? How functional programmers deals with such cases?

Aucun commentaire:

Enregistrer un commentaire