Pattern 17Memoization

Intent

To cache the results of a pure function call to avoid performing the same computation more than once

Overview

Since pure functions always return the same value for given arguments, it’s possible to replace a pure function call with cached results.

We can do this manually by writing a function that keeps track of its previous arguments. When it’s called, it first checks its cache to see if it has already been called with the passed-in arguments. If it has, it returns the cached value. Otherwise, it performs the computation.

Some languages provide first-class support for Memoization using higher-order functions. Clojure, for instance, has a function called memoize that takes a function and returns a new one that ...

Get Functional Programming Patterns in Scala and Clojure 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.