Reader small image

You're reading from  Expert C++ - Second Edition

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781804617830
Edition2nd Edition
Right arrow
Authors (5):
Marcelo Guerra Hahn
Marcelo Guerra Hahn
author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

Araks Tigranyan
Araks Tigranyan
author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

John Asatryan
John Asatryan
author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

Vardan Grigoryan
Vardan Grigoryan
author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

Shunguang Wu
Shunguang Wu
author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu

View More author details
Right arrow

Functional Programming

One of the most famous programming paradigms, which is object-oriented programming (OOP), provides us with a way of thinking about objects, thus expressing the real world in terms of classes and their relationships. Functional programming is an entirely distinct programming paradigm that allows us to focus on the functional structure rather than the physical structure of code. Functional programming has two benefits that make it worthwhile to learn and use. Firstly, it is a new paradigm, which encourages you to think differently. Flexible thinking is necessary for solving problems. People who adhere to a single paradigm tend to offer similar solutions to every problem, but the most elegant solutions require a broader perspective. Developers may solve problems even more effectively by using the new skills they get from mastering functional programming. Secondly, functional programming helps to cut down on software errors. Functional programming’s distinctive...

Technical requirements

The g++ compiler, along with the -std=c++20 option (which requires gcc10 or later), will be used to compile the examples in this chapter. You can find the source files used in this chapter at https://github.com/PacktPublishing/Expert-C-2nd-edition.

Functional programming revealed

As we mentioned earlier, functional programming is a programming paradigm. When building programs, you might think of a paradigm as a way of thinking. C++ is a multiparadigm language. It can be used to create programs using a procedural paradigm, which means executing statements one at a time. We have already spoken about the object-oriented approach, which divides a complicated system into objects that interact with each other. Contrarily, functional programming encourages us to break the system down into functions rather than objects. It operates with expressions rather than statements. In essence, you send an input to a function, which then returns an output. This can then be used as input for another function. Although it may appear straightforward at first, functional programming contains a number of rules and techniques that are challenging to understand at first. Nevertheless, if you succeed in doing so, a new way of thinking—the functional...

Using ranges

Ranges represent a collection of objects or anything iterable abstractly. The simplest definition merely requires begin() and end() to exist on the range. Ranges may be categorized in a variety of ways, but the most crucial one is according to the abilities of its iterators.

Ranges are connected to views. In this chapter, we will look at them both. They give us a general approach to creating and managing groupings of items. We often use iterators to loop through containers and work with their elements, as you have already seen. Thanks to iterators, we can have a loose connection between algorithms and containers.

For example, earlier, we applied count_if() to the vector, but count_if() is not aware of what container it was applied to. Take a look at the following declaration of count_if():

template <typename InputIterator, typename UnaryPredicate>constexpr typename iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator...

First-class and higher-order functions

In functional programming, functions are regarded as first-class objects (but you may also come across as first-class citizens). This implies that we should handle them as objects as opposed to a set of instructions. What difference does this make to us? The only criterion for a function to be considered an object at this point is its ability to be passed to other functions. Higher-order functions are defined as functions that accept other functions as arguments.

Programmers in C++ frequently pass one function to another. Here’s how to do it the old-school way:

typedef void (*PF)(int);void foo(int arg)
{
    // do something with arg
}
int bar(int arg, PF f)
{
    f(arg);
    return arg;
}
bar(42, foo);

We declared a pointer to a function in the code that was written here. With one integer parameter and no value returned, PF denotes a type definition for the function. This...

Pure functions

As we previously stated, a function is considered pure if it does not mutate the state. Pure functions may be thought of as less efficient than their non-pure counterparts, but they are wonderful since they prevent the majority of errors that develop in code as a result of state changes. Bugs are related to the program state in some way. Obviously, programs work with data, so they set up the functionality to modify the state and this leads to the expected results for the end user.

In OOP, we decompose the program into objects, each of which has a list of special features. In OOP, the state of an object is one of its core characteristics. OOP relies heavily on the ability to change an object’s state by interacting with it (in other words, calling its methods). Invoking a member function typically causes the object’s state to change. In functional programming, we organize code into a collection of pure functions, each of which has its own purpose and is...

Delving more deeply into recursion

The primary characteristics of a recursive function have previously been covered. Almost all the problems that can be solved with an iterative solution can also be solved with a recursive solution. Let us take a look at the simple recursive solution of one of the most famous problems: the calculation of the nth Fibonacci number:

int fibonacci(int n){
    if (n <= 1) return n;
    return fibonacci(n-1) + fibonacci(n - 2);
}

Let us illustrate the process that happens when the preceding function is called. In our example, we will consider that the argument passed to the function is 6, which means that n is equal to 6. The process starts like this:

Figure 8.5 – First call of the recursive fibonacci() function

Figure 8.5 – First call of the recursive fibonacci() function

The function calls itself until n is equal to or smaller than 1, but what happens when it becomes equal to 1?

Figure 8.6 – When the function reaches the base case

Figure 8.6 – When...

Metaprogramming in functional C++

One more paradigm of programming is metaprogramming. Due to the fact that we are not working with the regular process of programming, this method of coding is completely different. A program’s three stages of coding, compiling, and executing are referred to as a “regular process” in this context. It’s obvious that a program does what it’s supposed to do when it is executed. The compiler uses linking and compilation to generate an executable. Metaprogramming, on the other hand, is where the code is executed during the compilation of the code. This might sound magical if you are dealing with it for the first time. How can we execute code if the program doesn’t even exist yet? Recalling what we learned about templates in the previous chapters, we know that the compiler processes them with more than one pass. In the first pass, the compiler defines the necessary types and parameters that are used in the template...

Summary

In this chapter, we learned a new viewpoint on making use of C++. It may be used as a functional programming language since it is a multi-paradigm language.

We studied the fundamentals of functional programming, including folding, higher-order functions, and pure functions. Pure functions are those that don’t alter the state of the system. One advantage of pure functions is that they don’t create as many bugs as state modifications do.

Higher-order functions are functions that take or return other functions. Other than in functional programming, C++ programmers use higher-order functions when dealing with the STL.

Pure functions, along with higher-order functions, allow us to decompose the whole application into a big assembly line of functions. Each function in this assembly line is responsible for receiving data and returning a new, modified version of the original data (without mutating the original state). When combined, these functions provide a...

Questions

  1. List the advantages of ranges.
  2. What functions are known to be pure?
  3. What’s the difference between a pure virtual function and a pure function in terms of functional programming?
  4. What is folding?
  5. What is the advantage of tail recursion overhead recursion?

Further reading

For more information regarding what was covered in this chapter, please take a look at the following links:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Expert C++ - Second Edition
Published in: Aug 2023Publisher: PacktISBN-13: 9781804617830
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Marcelo Guerra Hahn

Marcelo Guerra Hahn, With over 18 years of experience in software development and data analysis, Marcelo Guerra Hahn is a seasoned expert in C++, C#, and Azure. As an Engineering Manager at Microsoft C++ Team and former leader of SoundCommerce's engineering team, Marcelo's passion for data and informed decision-making shines through. He shares his knowledge as a lecturer at esteemed institutions like Lake Washington Institute of Technology and University of Washington. Through this book, Marcelo aims to empower readers with advanced C++ techniques, honed by real-world experience, to become proficient programmers and skilled data analysts.
Read more about Marcelo Guerra Hahn

author image
Araks Tigranyan

Araks Tigranyan is a passionate software engineer at Critical Techworks, with an unwavering love for the world of programming, particularly in C++. Her dedication to crafting efficient and innovative solutions reflects her genuine passion for coding. Committed to excellence and driven by curiosity, Araks continuously explores new technologies, going above and beyond to deliver exceptional work. Beyond programming, Araks finds solace in sports, with football holding a special place in her heart. As an author, Araks aspires to share her profound expertise in C++ and inspire readers to embark on their programming journeys.
Read more about Araks Tigranyan

author image
John Asatryan

John Asatryan, the Head of Code Republic Lab at Picsart Academy, seamlessly blends his academic background in International Economic Relations from the Armenian State University of Economics with his ventures in technology and education. Driven by a genuine passion for coding, John's commitment to empowering aspiring developers is evident in his expertise in the field. His unwavering dedication to bridging the gap between education and technology inspires others to pursue their coding dreams.
Read more about John Asatryan

author image
Vardan Grigoryan

Vardan Grigoryan is a senior backend engineer and C++ developer with more than 9 years of experience. Vardan started his career as a C++ developer and then moved to the world of server-side backend development. While being involved in designing scalable backend architectures, he always tries to incorporate the use of C++ in critical sections that require the fastest execution time. Vardan loves tackling computer systems and program structures on a deeper level. He believes that true excellence in programming can be achieved by means of a detailed analysis of existing solutions and by designing complex systems.
Read more about Vardan Grigoryan

author image
Shunguang Wu

Shunguang Wu is a senior professional staff at Johns Hopkins University Applied Physics Laboratory, and received his PhDs in theoretical physics and electrical engineering from Northwestern University (China) and Wright State University (USA), respectively. He published about 50 reviewed journal papers in the area of nonlinear dynamics, statistical signal processing and computer vision in his early career. His professional C++ experience started with teaching undergraduate courses in the late 1990s. Since then he has been designing and developing lots of R&D and end-user application software using C++ in world-class academic and industrial laboratories. These projects span both the Windows and Linux platforms.
Read more about Shunguang Wu