I'm reading the Neal's Ford book *Functional Thinking* and now the whole idea of functional paradigm is becoming clearer.

The whole idea of functional programming (FP) today is to be able to leave *acidental complexities* up to the *language* or the *runtime* to solve for you. No one should have to manage memory into your daily work activities. This kind of problem is not related to your business at all! You are not being paid to solve it.

Luckily, most modern languages already have this task completely handled without your direct intervention.

There are many situations where this kind of *niceties* are introduced into the FP world, for example, if you use the **map** function in Clojure, you already gain parallel execution for free at runtime. If you use higher-order constructs, you enable the runtine to become smarter and to even rearrange execution in a most appropriate order.

This it not to say that you should not learn what is going on behind the scenes, but once you learn it you can use this knowledge in very succinct way.

Always learn one level of abstraction underneath you

However, let's explore the *memoization* mechanism for a second.

Imagine that you have a function that is very computational intensive, meaning that you spend most of your execution time to perform your desired operation on this function. And for your despair, the very same function is called several times inside your application. **How can we speed this up?**

Let's consider the task of classifying numbers into *perfect*, *abundant* and *deficient* accordingly with mathematical definitions of perfect numbers.

Example of a **Python** code to Classify numbers into *perfect*, *abundant* and *deficient*.

```
class Classifier:
@staticmethod
def sum_factors(number):
return sum(Classifier.factors_of(number))
@staticmethod
def factors_of(number):
filtered_list = filter(lambda x: (number % x == 0), range(1, number + 1))
return list(filtered_list)
@staticmethod
def is_perfect(number):
return Classifier.sum_factors(number) == 2 * number
@staticmethod
def is_abundant(number):
return Classifier.sum_factors(number) > 2 * number
@staticmethod
def is_deficient(number):
return Classifier.sum_factors(number) < 2 * number
```

Now, if you want to call this function on the numbers `[6, 25, 15000, 56000, 110560]`:

```
for el in [6, 25, 15000, 56000, 110560]:
print("The number {} is perfect? {}".format(el, Classifier.is_perfect(el)))
print("The number {} is abundant? {}".format(el, Classifier.is_abundant(el)))
print("The number {} is deficient? {}".format(el, Classifier.is_deficient(el)))
```

You will not probably like the result as the number that you want to classify gets bigger and bigger.

Same funcionality implemented in **Clojure**:

```
(defn- sum-of-factors [number]
(->> (range 1 (+ number 1))
(filter #(= 0 (rem number %)))
(reduce +)))
(defn is-perfect [number]
(= (sum-of-factors number) (* 2 number)))
(defn is-abundant [number]
(> (sum-of-factors number) (* 2 number)))
(defn is-deficient [number]
(< (sum-of-factors number) (* 2 number)))
```

And the same tests calls:

```
(doseq [el [6, 25, 15000, 56000, 110560]]
(println (str "The number " el " is perfect?" (is-perfect el)))
(println (str "The number " el " is abundant?" (is-abundant el)))
(println (str "The number " el " is deficient?" (is-deficient el))))
```

You will not like these results too. As we are not in a speed context between languages, I will place the time that the *Clojure* implementation took to perform these classifications.

Example of results. Showing only the *is_perfect* test.

```
el - 6: "Elapsed time: 0.122637 msecs"
el - 25: "Elapsed time: 0.071203 msecs"
el - 15000: "Elapsed time: 12.583968 msecs"
el - 56000: "Elapsed time: 32.59634 msecs"
el - 110560: "Elapsed time: 47.281954 msecs"
```

In order to perform all the classifications, the code took **170 msecs**.

Ok, we understand the problem now. The whole idea of **memoization** is to **cache** some results in order to gain speed when you compute that value again. This is very nice and simple: **you exchange memory space for speed**. Instead of computing the whole thing again, you will only perform a lookup into some data structure.

However, you see functional programming concepts kick-in again. In order to implement this sort of caching, you need that your function or method to be **pure**, in other words, if you pass the same inputs you always get the same output!

Implementing **caching** in Python to simulate memoization.

```
class ClassifierCached:
def __init__(self):
self.sum_cache = {}
def sum_factors(self, number):
if not number in self.sum_cache:
self.sum_cache[number] = sum(self.factors_of(number))
return self.sum_cache[number]
def factors_of(self, number):
filtered_list = filter(lambda x: (number % x == 0), range(1, number + 1))
return list(filtered_list)
def is_perfect(self, number):
return self.sum_factors(number) == 2 * number
def is_abundant(self, number):
return self.sum_factors(number) > 2 * number
def is_deficient(self, number):
return self.sum_factors(number) < 2 * number
```

If you pay attention, you will see that I haven't done much in order to implement this simple caching mechanism. However, what happened?

- I have to choose the data structure to store the data (a dictionary
`sum_cache`

) - I have to manage the lookup into the data structure
- I have to manage the population of the data structure
- I have to change the
`staticmethod`

functions to become instance methods, because now I have a state to manage.

Let's take a look at the **Clojure** version:

```
(defn- sum-of-factors-non-cached [number]
(->> (range 1 (+ number 1))
(filter #(= 0 (rem number %)))
(reduce +)))
(def sum-of-factors
(memoize sum-of-factors-non-cached))
```

I just renamed the old implemented function to become `sum-of-factors-non-cached`

and created a new one using the function `memoize`

. That's it.

Now, the whole call cost **80 msecs**. As worse as your high-demanding function become, the clearer become the advantages of *memoization*.

What's the beauty on the Clojure version? I delegate to the *language* all the choices that I had to make in the Python version. The runtime is taking care of all the details for me.

Let's keep focused on the business problems we want to solve!!