We all know C++ as Object Oriented Programming language but just like many other widely used object-oriented languages (Java, C# etc), C++ is slowly adopting more features related to functional languages. Its default behavior is imperative but you can write code in a functional style in C++ even more easily than other pure imperative languages like C. Const keyword can be applied to almost everything in C++ which enforce a functional style of programming. As functional programming is a new concept, it can give headaches to developer.
This new style of coding is getting popular these days as it makes code readable, reasonable and more sensible to understand.
In this article, I will explain, the basics of functional programming in C++. But still it is an intermediate topic and you should be familiar with C++ and OOP to understand functional programming.

What is functional programming?

Functional programming languages are designed to handle symbolic computation and list processing applications. Functional programming is based on functions – just like functions exist in mathematics. Some of the popular languages that use mathematical functions are Lip, Python, Erlang etc.
Functional programming languages use conditional expressions and recursion by supporting high order functions and lazy-evaluation features. Functional programming doesn’t support conditional statements like loops, if-else. It uses functions and functional calls instead. It supports popular OOP concepts such as Abstraction, Encapsulation, Inheritance, and Polymorphism. It is a declarative type of coding style. It primarily focuses on ‘what to solve’ rather than ‘how to solve’.
The only drawback functional programming has its requirement for large memory space. As it doesn’t have a state, new objects need to be created every time you have to perform actions through it.

Why functional programming?

FP isn’t a new concept in computer science but only recently, it got so much popularity. The reason behind its growing usage is its efficiency and ability to do parallel processing. It makes code easier to understand and predictable for developers. What predictable means is that the programming is based on pure functions. It would return the same result if given the same arguments. There won’t be a case when you give the same parameter and have different results. Writing code in a modular way makes it easier to debug and test. You don’t have to mock everything. You can use unit testing to test these functions.

This biggest advantage of using functional programming is parallel processing. The code will be executed on multiple processing units because it doesn’t use or access global variables.

Functional Programming is based on Lambda calculus

C++11 introduced lambda functions. Lambda calculus is a framework developed by Alonzo to study functions. It defines, what is computable. Anything that can be computed by Lambda is computable. It is something similar to a Turing machine in its ability to compute. Almost all of the functional programming languages are based on this and use Lambda to describe functions and their evaluation.

Lambdas are anonymous in-place functions which means it doesn’t own a name specifically. Here is hello world example in lambda.

[](){

cout << “Hello World! “;

}();
[] is lambda closure or capture list
() is function parentheses and contains an argument list.
{} contains the body of code
(); Lambda implementation cannot call itself automatically. We need to call these explicitly. To call the lambda in-place in a similar way, we append (); at the end.

To write a function that would add two add integers in lambda, write the following code:

auto sum = [](int a, int b){ return a+b; };
cout << sum(2,5)<<endl;

Here auto is used to infer the data type of the variables by looking at the values at compile time.
To return a value from Lambda as function, the return type of a lambda is depicted using -> syntax as.

[]() -> int{
int a =2, b =5,c;
c = a+b;
return c;
}();

You can also save the value being returned by lambda in any variable as

int sum = []() -> int{
int a =2, b =5,c;
c = a+b;
return c;
}();

The basic concept of functional programming

FP is mostly based on the following concepts:

Pure Function

As we have already discussed pure functions, these make the programming quite predictable. These functions have two main properties. (1) They always produce the same output every time you give the same parameters. (2) They don’t modify global variables or any other variable.
The following is an example of the pure function:

product (x, y) {return x*y; }

Recursion

There is no for or while loop in functional programming. Functions repeatedly call themselves through recursion until it reaches the base case.

fib(n) { 
if (n <=1 ) return 1;
else return fib(n-1) + fib(n-2);
}

Referential Transparency

In functional programming, the state of any variable is constant at any time. Variables once defined do not change values throughout the program. If we have to store a new value, we have to declare new variables. This would eliminate any chance of replacing variable values with new values at any point of execution

xy = xy + c ; // this isn’t referentially transparent as the value of variable xy is being changed.

First class and high order functions

High order functions are functions that take first class functions as arguments and these can also return functions. In FP, first class functions are considered as first class variables to be passed as parameters in high order functions.

Related Articles

Calculate Average of Numbers in Arrays using C++

Introduction to C#

Last modified: February 7, 2019

Comments

Write a Reply or Comment

Your email address will not be published.