THE NEED TO REMEMBER

Computers are great at remembering things. In fact, if you look at typical business applications, you could easily get the impression that remembering things, not computing things, is the main purpose of computers these days. The data that computer programs work with is more often stored in a database than it is actually created or computed during the run of those programs. The ubiquity of database systems is testament to this fact.

In functional programming, as has been said before, the focus is on applying functions as opposed to handling state, and arguably all persisted data is a kind of state. Of course, handling persisted data is a reality of computer applications today, so functional programming has to find a way to deal with that. The details of accessing data from databases are not the subject of this chapter, but there is a more general need to remember data in functional programming: that which has been returned from calculations before, and therefore shouldn’t be calculated again.

There are two main cases where you want to remember results of computations performed previously, and both of those are covered in this chapter. The first is precomputation, which is when you purposefully compute values before the actual algorithm runs that uses those values. The second is the situation in which you have function calls that are performed repeatedly, with the same set of arguments, and you want to optimize by storing and reusing the values that have been ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.