Lambdas are one of the totally new addition to C++11 and has changed the way we write the code in C++. Any modern C++ code is incomplete without using lambdas which allow creation of in-place anonymous functions and transforms C++ into a full fledged Functional Programming Language.

Since the syntax as well as usage is relatively new, many C++ programmers still find it bit difficult to write and the usage scenarios.

This blog intends to describe the syntax, usage, and applicabilities of lambdas and how it helps in writing short, maintainable, functional and modern C++ code.

But before understanding what are lambdas and using the same, we need to understand a bit about Functional Programming

What is Functional Programming

In a nutshell, Functional Programming is all about writing the program functions similar to mathematical function. For example, consider the mathematical function

f(x)2 = x * x

This function returns the square of x and is an independent function which neither depends upon, nor impacts anything outside the function scope. Given an input x , the output will always be x * x all the time.

Let’s also consider polynomial mathematical functions like (x + y)2 (whole square) which is written as

f(x,y)2 = x2 + y2 + 2xy

This function can simply be broken into multiple smaller functions as

f(x,y)2 = f(x)2 + f(y)2 + f(2xy)

Here also, the function outputs are dependent only upon the input parameters. With a given input, the function will always generate the same output.

The other characteristics of a function are that the parameters passed in the argument are Immutable. In both the above functions f(x)2 and f(x,y)2 , the paramaters x and y are immutable. They are used for calculations, but are not changed because mathematical functions always generate new values out of existing ones. That’s the reason in maths, we don’t see a function like

f(x) = x++

But functions which do x++ is prevalent in C++ and in other programming languages. Functional Programming wants us to write code like mathematical functions where the functions are

Neither dependent upon, nor change anything which is external to the function. Everything is Immutable, if we change something it will create a new one rather than changing existing items

Why use Functional Programming?

In a world of multi core CPU(s) where the program runs in parallel, a functional program can safely execute of multiple CPU(s) with worrying about excessive locking because it doesn’t use or modify any global resources.