How to do functional programming in C++? Complete guide with examples (2022)

How to do functional programming in C++? Complete guide with examples (2022)

In functional programming, we use functions in C++ to write code. But people wonder why they should use functions when you can write the entire code in one main function. There must be something that makes it a necessary skill for a coder to have. Let’s check out.

Introduction

Functional programming is a form of programming that operates on the concept of using functions to perform calculations and other tasks. It is an alternative to traditional object-oriented programming, which relies on objects and classes to store and manipulate data. Functional programming allows for a more concise and efficient coding style and is becoming increasingly popular among developers. We will talk about functional programming in C++ in this article. We will also look at some of the concepts behind functional programming, as well as examples of code in C++ to illustrate how to go about implementing it.

What is Functional Programming?

According to Wikipedia, “Functional programming is a programming paradigm that focuses on the use of functions as the primary building block for software development.�� This means that it is a programming style that emphasizes the use of pure functions that have no side effects and are easy to reason about. It also emphasizes the use of immutability, which means that variables cannot be changed once we declare them.

Benefits of Functional Programming in C++

Functional programming in C++ offers several benefits, such as improved code readability, improved code maintainability, reduced complexity, and improved code performance. Additionally, functional programming in C++ encourages the use of abstractions, which allows code to be written more quickly and with fewer bugs.

Functional Programming in C++

The C++ programming language offers a variety of features that make it easier to write functional programs. First is the ability to define and use functions. This means that instead of writing code directly in the main program, we can create functions that can be called from other parts of the code. There are more tools which are as follows:

Lambda Expressions

Lambda expressions are a powerful feature of C++ that allows for the creation of anonymous functions. These functions can take arguments and return a value and can be used to create higher-order functions such as map and filter algorithms. Lambda expressions are also useful for writing callbacks and for creating function objects.

Standard Template Library (STL)

For functional programming in C++, the Standard Template Library (STL) offers a library of general-purpose algorithms and data structures. The STL includes functions such as map and filter, which are useful for applying a function to a collection of elements. Additionally, the STL includes algorithms such as sort, which can be used to sort a collection of elements.

Function Objects

Function objects are instances of classes that contain a single function. These objects can be used to encapsulate a function, making it easier to pass around and use. Function objects are also useful for creating higher-order functions, such as map and filter algorithms.

Examples of Functional Programming in C++

Now that you have a better understanding of functional programming in C++, let’s look at some examples.

Example 1

In our 1st example, we will be Filtering a vector using a higher-order function and a lambda expression.

Let’s say we want to filter out all the odd numbers from a vector of integers. One way to do this is to use a higher-order function called std::remove_if, which takes a predicate function as an argument and removes all elements that satisfy the predicate. We can use a lambda expression as the predicate function to check if an element is odd.

The code for the same is as follows:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> z{24, 57, 98, 101, 49, 88, 28};

  //Predicate function using a lambda expression
  auto is_odd = [](int y) { return y % 2 == 1; };

  //std::remove_if to filter ;out the odd numbers
  z.erase(std::remove_if(z.begin(), z.end(), is_odd), z.end());

  //Print result
  for (const auto& y : z) {
    std::cout << y << " ";
  }
  std::cout << std::endl;

  return 0;
}Code language: C++ (cpp)
Output

Click Here to try this code by yourself.

Example 2

Now for our next example, we will be mapping a vector using a higher-order function and a lambda expression.

Suppose we have a vector of integers and we want to multiply each element by 2. We can use a higher-order function called std::transform to apply a function to each element of the vector. We can use a lambda expression as the function to multiply each element by 2:

The code for the same is as follows:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> z{3, 7, 5, 8, 12};

  // Defining the mapping function using a lambda expression
  auto multi_by_2 = [](int y) { return 2 * y; };

  //std::transform to apply the mapping function to each element of the vector
std::transform(z.begin(), z.end(), z.begin(), multi_by_2);

// Print the result
for (const auto& y : z) {
std::cout << y << " ";
}
std::cout << std::endl;

return 0;
}Code language: C++ (cpp)
Output

Click Here to try this code by yourself.

Example 3

For the last example for today’s article, we will be using the accumulate function to reduce a vector to a single value.

Suppose we have a vector of integers and we want to compute their sum. We can use the std::accumulate function to reduce the vector to a single value.

The code for the same is as follows:

#include <numeric>
#include <iostream>
#include <vector>

int main() {
std::vector<int> z{23, 44, 51, 111, 67};

// Using the std::accumulate to compute the sum of the vectors elements
int total_sum = std::accumulate(z.begin(), z.end(), 0);

// Printing the result
std::cout << "Sum of the elements is: " << total_sum << std::endl;

return 0;
}Code language: C++ (cpp)
Output

Click Here to try this code by yourself.

Applications of Functional Programming


We use Functional programming in C++ in a variety of real-life applications including embedded systems and robotics, game development, high-performance, and distributed applications, financial applications, AI and machine learning systems, web development, computer vision, and natural language processing. In these areas, we use functional programming to provide reliable, efficient, and fast code, create complex data structures, maintain a secure system, and build efficient algorithms. It is a powerful tool for creating robust and powerful applications in a variety of fields.

Conclusion

In conclusion, functional programming is a powerful way of writing code in C++. It allows for the creation of more expressive and efficient code by taking advantage of concepts such as lambda functions, higher-order functions, currying, and composition. Keep in mind that there are a number of tools available to help with this approach, and it’s important to understand the advantages and disadvantages of each. As you become more comfortable with functional programming, you should be able to create more powerful and efficient applications.

I hope you found this article helpful; queries are always welcome in the comment section. We’ll be back again with some more amazing articles; till then, keep coding and have a fantastic day ahead!

Sharing is caring

Did you like what Pravin Gupta wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far