Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Expert C++ - Second Edition

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

Product type Book
Published in Aug 2023
Publisher Packt
ISBN-13 9781804617830
Pages 604 pages
Edition 2nd Edition
Languages
Authors (5):
Marcelo Guerra Hahn Marcelo Guerra Hahn
Profile icon Marcelo Guerra Hahn
Araks Tigranyan Araks Tigranyan
Profile icon Araks Tigranyan
John Asatryan John Asatryan
Profile icon John Asatryan
Vardan Grigoryan Vardan Grigoryan
Profile icon Vardan Grigoryan
Shunguang Wu Shunguang Wu
Profile icon Shunguang Wu
View More author details

Table of Contents (24) Chapters

Preface 1. Part 1:Under the Hood of C++ Programming
2. Chapter 1: Building C++ Applications 3. Chapter 2: Beyond Object-Oriented Programming 4. Chapter 3: Understanding and Designing Templates 5. Chapter 4: Template Meta Programming 6. Chapter 5: Memory Management and Smart Pointers 7. Part 2: Designing Robust and Efficient Applications
8. Chapter 6: Digging into Data Structures and Algorithms in STL 9. Chapter 7: Advanced Data Structures 10. Chapter 8: Functional Programming 11. Chapter 9: Concurrency and Multithreading 12. Chapter 10: Designing Concurrent Data Structures 13. Chapter 11: Designing World-Ready Applications 14. Chapter 12: Incorporating Design Patterns in C++ Applications 15. Chapter 13: Networking and Security 16. Chapter 14: Debugging and Testing 17. Chapter 15: Large-Scale Application Design 18. Part 3:C++ in the AI World
19. Chapter 16: Understanding and Using C++ in Machine Learning Tasks 20. Chapter 17: Using C++ in Data Science 21. Chapter 18: Designing and Implementing a Data Analysis Framework 22. Index 23. Other Books You May Enjoy

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 2023 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}