A Small Aside: Memoization

Learn about memoization relation with pure functions.

In an earlier chapter, we briefly discussed how FP could be less performant than other styles of programming in some situations. Besides the advantages of high-level programming when it comes to optimizations that an engine might perform without us even knowing, one specific and powerful tool is available to the functional programmer: memoization.

Memoization relation with pure functions

Memoization gains its power from pure functions. Because we know that a pure function’s result is only dependent on what we pass in, we can deduce that if we calculate the result for a given set of parameters, we can return that result whenever the same parameters are passed to us in the future. In essence, memoization is a function cache that saves results and returns them whenever a future call uses parameters we’ve seen before. For compute-intensive functions, this can be a huge win, even if it comes at the cost of additional storage. Calculating Fibonacci numbers is a typical memoization example. The same parameters pass in more than once, but calculating large numbers is compute-intensive and the cost of storing them is negligible.

In our example application, we have two considerations. First, do we have functions that are likely to be called with the same parameters? Second, are those functions compute-intensive? None of our functions comply with both requirements. But let’s pretend that our reducedStatsForFailure function has some important calculations to perform and memoize it. First, add the helper library fp-ts-std to our dependencies. Then, add the following to our transformations:

Get hands-on with 1400+ tech skills courses.