Closures Vs Currying Vs Anonymous functions

ยท

5 min read

Closures Vs Currying Vs Anonymous functions

Photo by Luca Bravo on Unsplash

Closures, Currying and Anonymous functions are one of the most misunderstood programming concepts due to their similarities in structure and relativity ro functional programming. In this post we would be breaking down the intricacies of these concepts and by the time you are done with reading this, you'll be able to differentiate and apply them in your next project; that's if you are using the functional approach.

Closures

A closure is a function-like object that acts as a record that captures the data (Free variables etc) of its immediate environment (The function it exists in). You can see Closures as a screenshot or snapshot mechanism that exists inside functions. Closures keep the variables and data in a function alive & accessible after the function call. The closure originates from the functional programming paradigm but many multi-paradigm languages such as JavaScript and Python, integrated it into their ecosystem.

You can see Closures as child functions which has a binding to the lexical environment of it parent function (outer environment).

Here is an Example:

def outer(a):
   def inner_child(b):
      return a+b
   return inner_child

closure=outer(1)

if closure(2)==3 #True

Breakdown:

We created a function named outer which takes an argument a

Inside outer function we declare another function inner_child which takes a parameter b and adds it to the parameter of its parent function and returns the value. The parent function outer returns the inner_child as a function object yet to be called.

We create a variable named closure we assign it the outer function call as its value, passing in an argument 1. The variable closure stores the return value of outer which is the inner_child function yet to be called(That's the closure), you can see that due to the fact inner_child hasn't been called the parameter or free variable a was kept alive and was not destroyed after the outer function call as it should normally. That is the power of closures it keeps the local variables alive even after function calls.

In the last line the closure variable closure is now called and an argument 2 is now passed in (The closure variable is just the inner_child function object under the hood). When closure was called and given an argument, the inner_child function was called to get to work. The inner_child function object used the variable a (which it captured from the lexical scope of its parent's outer function environment; a classic closure!๐Ÿ˜€) and added it to its own local variable b and returned their summed value. That is why we can assert that if closure(2)==3 #True

This is a classic example of a closure; with this example you should understand the concept of closures.

Let's Explore The Other Concepts ๐Ÿ˜

Currying

Definition

Currying is the process of breaking down a function with multiple arguments to series of related child's functions that would handle one argument at a time.

Curried functions syntactically look very similar to Closures; but in the midst of their many similarities they have differences in their purpose.

Currying is not used to capture the lexical environment of its outer scope, While Closures aren't used to breakdown multi-argument functions.

P.S: A function can also be curried and contain closures in it, that is the case for many curried functions. Infact most closures are used to curry functions. Currying is more like a process and not an object ๐Ÿ˜‰

Example:

This is a normal multi-argument function:

     def sum(a,b,c):
         return a+b+c
function sum(a, b, c) {
  return a + b + c;
}

This is its curried version:

function sum(a) {
  return function(b) {
    return function(c) {
      return a + b + c;
    };
  };
}

var result = sum(5)(10)(15);
console.log(result);  // Output: 30
def sum(a)
  return lambda b: lambda c: a+b+c
result = sum(5)
partial_result = result(10)
final_result = partial_result(15)

print(final_result)  # Output: 30

You see that's what currying looks like!

Anonymous Functions

Definition

Anonymous functions are functions without identifiers. They are also known as lambda functions, and they play a very important role in the functional programming. The use cases of anonymous functions ranges from being used as closures, to being passed as arguments to high-order functions, to being used for currying. The uses of Anonymous functions are as vast as the ocean ๐Ÿ˜„

Example

This anonymous function is performing a curry on the function a() while being also a closure to the function.

function a(x){

  return function(b){
    return x+b
} 
 }
def a(x):
 return lambda b: x+b

Here's another example of an anonymous function being an argument to a higher-order function:

const arr=[1,2,3,4,5,6,7,8]
const new_arr= arr.filter((x)=> x%2!==0)
arr = [1, 2, 3, 4, 5, 6, 7, 8]
new_arr = list(filter(lambda x: x % 2 != 0, arr))

There are lots and lots of real-world use cases of anonymous functions, most operations of function-oriented programs run on anonymous functions as their atomic backbone.

Summary

The difference in Closures, Currying and Anonymous Functions lies in their functionality.

Closures are used to capture its surrounding lexical environment; a closure is a function object.

Currying is used to take multi-arguments in a large function sequentially, where one argument would be taken at a time. Currying is a process.

Anonymous Functions are simply functions without identifiers(names). An anonymous function is simply a function.

You can see that these concepts can be used together to create performant and efficient programs. These are just building blocks waiting to be combined in harmony to create functional programs.

Thank you for reading!

I am Paul Fruitful a Software Engineer keen about breaking down complex computational theories and concepts, Design patterns, Programming Paradigms, Technologies, System designs, Data Structures and algorithms and lots more using written articles and video tutorials.

Check out my Youtube https://www.youtube.com/@paulfruitful

Follow me to learn more!

ย