DEV Community

Cover image for Closures πŸ«‚ Memoisation
Emmanuel (Emmo00)
Emmanuel (Emmo00)

Posted on

Closures πŸ«‚ Memoisation

In functional programming, closure refers to the ability of a function to access and utilize variables from its lexical scope, even after that scope has finished executing. Now, Lexical scope basically refers to the environment/location a variable is defined/declared within the source code.

Closures (forever) remember the scope they were declared in for as long as they exist.

Example of closures

In the above example, the code uses a closure to create a function object that provides controlled access to a private variable. The get method allows you to retrieve the value, and the set method allows you to update it.

This may sound obvious, but it can be very useful in implementing a technique called "memoisation"

Memoization is an optimization technique used in computer science to improve the performance of programs. It's especially useful for improving the performance of functions that are computationally expensive and called multiple times with the same inputs.

Memoisation can basically be described as when expensive operations are run early, and their results cached for later use in the program.

Example implementation of Memoisation

In the above example, the function square_memoise uses memoization by avoiding unnecessary computations for repeated function calls with the same arguments, potentially improving performance.

In conclusion, closures and memoization are powerful tools that enhance the capabilities of functional programming. Closures provide a way to create private variables within functions, leading to better data encapsulation and code organization. Memoization, on the other hand, optimizes program performance by caching the results of expensive calculations, preventing redundant work. By understanding and utilizing these techniques, you can write cleaner, more efficient, and maintainable code.

Top comments (2)

Collapse
 
michvista profile image
Michelle

Nice and simple, thanks

Collapse
 
emmo00 profile image
Emmanuel (Emmo00)

I'm glad you like it