Posts Tagged ‘Functional Programming’

Memoization Using C#

Posted: April 5, 2020 in .NET, C#
Tags: , ,

Memoization is a technique very commonly used in Functional Programming to improve the performance of a function execution by caching its results. Here, caching helps to avoid the expensive computations of a complex function.

Before getting into the implementation which in my opinion is pretty straightforward to understand let put in few lines on the term itself. This activity of caching the results is similar to memorizing the already computed results but then why “r” is missing and its called memoization ? This is because the term has been derived from memo which is an American English for the Latin word memorandum. So it’s memo-ization.

In order to this we normally write a Higher Order Function (HOF) which accepts the function to be memoized as input and returns a closure of same as type as the input function and wraps it within the logic for caching as shown in the sample below:

image

Now let’s try to invoke this function. We will use a simple factorial function for memoization here.

image

We are making three calls to the memoized version of the Factorial function, the last call is made with a repeated parameter.

image 

For the first two calls the function will be executed and the results of the third call are picked up from the cache.

image

We can write the Memoize function in a much more concise manner as shown below:

image

We can also make the function thread-safe using ConcurrentDictionary for caching.

image

For the past couple of months I have been looking into different aspects of functional programming and learning languages like F# and Haskell.While discussing about this with my friends ( particularly to those who are developers without much academic inclination) I find it sometimes a bit difficult to explain the essence of functional programming as many are not much aware of the basic driver behind the design of the imperative languages.After going through couple of papers and articles I found the paper by John Backus titled Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs captures what I was looking for but in a rather complex fashion.In this post I will try to explain the basic issues with imperative languages and essence of functional languages in a simpler fashion.

(more…)