Hands-On Functional Programming with C++
eBook - ePub

Hands-On Functional Programming with C++

An effective guide to writing accelerated functional code using C++17 and C++20

Alexandru Bolboaca

Share book
  1. 358 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Functional Programming with C++

An effective guide to writing accelerated functional code using C++17 and C++20

Alexandru Bolboaca

Book details
Book preview
Table of contents
Citations

About This Book

Learn functional programming and build robust applications using the latest functional features in C++

Key Features

  • Learn programming concepts such as loops, expressive code, and simple parallelization
  • Understand the working of Lambdas and Currying and write Pure functions
  • Explore event sourcing and other functional patterns to improve the efficiency of your applications

Book Description

Functional programming enables you to divide your software into smaller, reusable components that are easy to write, debug, and maintain. Combined with the power of C++, you can develop scalable and functional applications for modern software requirements. This book will help you discover the functional features in C++ 17 and C++ 20 to build enterprise-level applications.

Starting with the fundamental building blocks of functional programming and how to use them in C++, you'll explore functions, currying, and lambdas. As you advance, you'll learn how to improve cohesion and delve into test-driven development, which will enable you in designing better software. In addition to this, the book covers architectural patterns such as event sourcing to help you get to grips with the importance of immutability for data storage. You'll even understand how to "think in functions" and implement design patterns in a functional way.

By the end of this book, you'll be able to write faster and cleaner production code in C++ with the help of functional programming.

What you will learn

  • Understand the fundamentals of functional programming
  • Structure your code by understanding the building blocks of functional programming
  • Compare design styles in functional programming and object-oriented programming (OOP)
  • Use the concept of currying to create new functions in C++
  • Become skilled at implementing design patterns in a functional way
  • Get to grips with multithreading by means of functional programming
  • Learn how to improve memory consumption when using functional constructs

Who this book is for

This book is for C++ developers who want to learn functional programming but have little to no knowledge of the paradigm. Although no prior knowledge of functional programming is necessary, basic C++ programming experience will help you understand key concepts covered in the book.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Hands-On Functional Programming with C++ an online PDF/ePUB?
Yes, you can access Hands-On Functional Programming with C++ by Alexandru Bolboaca in PDF and/or ePUB format, as well as other popular books in Computer Science & Computer Science General. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781789809213
Edition
1

Section 1: Functional Building Blocks in C++

In this section, we will learn about the basic building blocks of functional programming and how to use them in C++. First, we will look at what functional programming is and how it is different from and similar to object-oriented programming (OOP). Then, we will dive into the fundamental idea of immutability and learn how to write pure functions in C++—that is, functions that don't change state. We will then learn how to use lambdas and how to write pure functions using them.
Once we master those building blocks, we can move on to operations with functions. In functional programming, functions are data, so we can pass them around and make operations with them. We will learn about partial application and currying, two fundamental and closely-related operations. We will also see how to compose functions. These operations will take us from simple functions to very complex ones with just a few lines of plumbing code.
The following chapters will be covered in this section:
  • Chapter 1, An Introduction to Functional Programming
  • Chapter 2, Understanding Pure Functions
  • Chapter 3, Deep Dive into Lambdas
  • Chapter 4, The Idea of Functional Composition
  • Chapter 5, Partial Application and Currying

An Introduction to Functional Programming

Why is functional programming useful? Functional programming constructs have popped up in all major programming languages in the past decade. Programmers have enjoyed their benefits—simplified loops, more expressive code, and simple parallelization. But there's more to it—decoupling from time, enabling opportunities to remove duplication, composability, and a simpler design. Higher adoption of functional programming (including the large-scale adoption of Scala in the financial sector) means more opportunities for you once you know and understand it. While we will take a deep dive into functional programming in this book to help you learn, remember that functional programming is another tool to add to your toolbox—one that you can choose to use when the problem and the context fits.
The following topics will be covered in this chapter:
  • An introduction to functional programming and an examination of how you've already been using functional constructs
  • Structured loops versus functional loops
  • Immutability
  • Object-oriented programming (OOP) versus functional design
  • Composability and removing duplication

Technical requirements

The code works with g++ 7.3.0 and C++ 17; it includes a makefile for your convenience. You can find it in the GitHub repository (https://github.com/PacktPublishing/Hands-On-Functional-Programming-with-Cpp) in the Chapter01 directory.

An introduction to functional programming

My first experience with functional programming was at university. I was a 20-year-old geek who was interested in Sci-Fi, reading, and programming; programming was the highlight of my academic life. Everything to do with C++, Java, MATLAB, and a few other programming languages that we used was fun for me. Unfortunately, I can't say the same thing about the disciplines around electrical engineering, circuits, or compiler theory. I just wanted to write code!
Based on my interests, functional programming should have been a very fun course for me. Our teacher was very passionate. We had to write code. But something went wrong—I didn't click with what the teacher was telling us. Why were lists so interesting? Why was the syntax so backward and full of parentheses? Why would I use these things when it was much simpler to write the same code in C++? I ended up trying to translate all the programming constructs I knew from BASIC and C++ into Lisp and OCaml. It completely missed the point of functional programming, but I passed the course and forgot about it for many years.
I imagine that many of you can relate to this story, and I have a possible reason for this. I now believe that my teacher, despite being extremely passionate, used the wrong approach. Today, I understand that functional programming has a certain elegance at its core, due to its strong relationship with mathematics. But that elegance requires a sense of insightful observation that I didn't have when I was 20, that is, a sense that I was lucky to build on after years of various experiences. It's obvious to me now that learning functional programming shouldn't be related to the ability of the reader to see this elegance.
So, what approach could we use instead? Thinking about the past me, that is, the geek who just wanted to write code, there's only one way to go—look at the common problems in code and explore how functional programming reduces or removes them entirely. Additionally, start from the beginning; you've already seen functional programming, you've already used some of the concepts and constructs, and you might have even found them very useful. Let's examine why.

Functional programming constructs are everywhere

Around 10 years after I finished the university functional programming course, I had a casual chat with my friend, Felix. As any two geeks, we would rarely see each other, but we had, for years, an ongoing conversation on instant messaging discussing all kinds of nerdy topics and, of course, programming.
Somehow, the topic of functional programming came up. Felix pointed out that one of my favorite and most enjoyable programming languages, LOGO, was, in fact, a functional programming language.
LOGO is an educational programming language whose main characteristic is utilization of so-called turtle graphics.
It was obvious in retrospect; here is how to write a function that draws a square in the KTurtle version of LOGO:
learn square {
repeat 4 {forward 50 turnright 90}
}
The result is shown in the following screenshot:
Can you see how we're passing two lines of code to the repeat function? That's functional programming! A fundamental tenet of functional programming is that code is just another type of data, which can be packed in a function and passed around to other functions. I used this construct in LOGO hundreds of times without making the connection.
This realization made me think: could there be other functional programming constructs that I've used without knowing? As it turns out, yes, there were. In fact, as a C++ programmer, you've most likely used them as well; let's take a look at a few examples:
int add(const int base, const int exponent){
return pow(base, exponent);
}
This function is a typical example of recommended C++ code. I first learned about the benefits of adding const everywhere from the amazing books of Bertrand Meyer: Effective C++, More Effective C++, and Effective STL. There are multiple reasons this construct works well. First, it protects the data members and parameters that shouldn't change. Second, it allows a programmer to reason more easily about what happens in the function by removing possible side effects. Third, it allows the compiler to optimize the function.
As it turns out, this is also an example of immutability in action. As we'll discover in the following chapters, functional programming places immutability at the core of the programs, moving all side effects to the edges of the program. We already know the basic construct of functional programming; to say that we use functional programming just means to use it much more extensively!
Here's another example from STL:
std::vector aCollection{5, 4, 3, 2, 1};
sort (aCollection.begin(), aCollection.end());
The STL algorithms have great power; this power comes from polymorphism. I'm using this term in a more fundamental sense than in OOP—it merely means that it doesn't matter what the collection contains, because the algorithm will still work fine as long as a comparison is implemented. I have to admit that when I first understood it, I was impressed by the smart, effective solution.
There's a variant of the sort function that allows the sorting of elements even when the comparison is not implemented, or when it doesn't work as we'd like; for example, when we are given a Name structure, as follows:
using namespace std;

// Parts of code omitted for clarity
struct Name{
string firstName;
string lastName;
};
If we'd like to sort a vector<Name> container by first name, we just need a compare function:
bool compareByFirstName(const Name& first, const Name& second){
return first.firstName < second.firstName;
}
Additionally, we need to pass it to the sort function, as shown in the following code:
int main(){
vector<Name> names = {Name("John", "Smith"), Name("Alex",
"Bolboaca")};

sort(names.begin(), names.end(), compareByFirstName);
}
// The names vector now contains "Alex Bolboaca", "John Smith"
This makes a kind of higher-order function. A high-level function is a function that uses other functions as parameters in order to allow higher levels of polymorphism. Congratulations—you've just used a second functional programming construct!
I will go as far as to state that STL is a good example of functional programming in action. Once you learn more about functional programming constructs, you'll...

Table of contents